<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class C_kudalautapi extends CI_Controller {
    
  function __construct(){
    parent::__construct();    
    $this->load->model('m_masters');
        $this->load->helper(array('url','html','form'));
        $this->load->library('session');
    ini_set('max_execution_time', 0);    
    ini_set('memory_limit', '20000M');
    $this->load->library('GoogleAuthenticator');
    date_default_timezone_set("Asia/Jakarta");

  }
 
 
  public function index()
  {
    //   show_404($page = 'gasdgasdg', $log_error = TRUE);

        echo "hahahahahaha";
  }
  
  public function tidythisdate($dirtydate)
  {
      $tahun = substr($dirtydate, 7,4);
      $tanggal = substr($dirtydate, 0,2);
      $jam = substr($dirtydate, 12, 10);
      
      $bulan = substr($dirtydate, 3,3);
      
      if ($bulan == 'Jan')
      {
          $bulan = '01';
      }
      else if ($bulan == 'Feb')
      {
          $bulan = '02';
      }
      else if ($bulan == 'Mar')
      {
          $bulan = '03';
      }
      else if ($bulan == 'Apr')
      {
          $bulan = '04';
      }
      else if ($bulan == 'May')
      {
          $bulan = '05';
      }
      else if ($bulan == 'Jun')
      {
          $bulan = '06';
      }
      else if ($bulan == 'Jul')
      {
          $bulan = '07';
      }
      else if ($bulan == 'Aug')
      {
          $bulan = '08';
      }
      else if ($bulan == 'Sep')
      {
          $bulan = '09';
      }
      else if ($bulan == 'Oct')
      {
          $bulan = '10';
      }
      else if ($bulan == 'Nov')
      {
          $bulan = '11';
      }
      else if ($bulan == 'Dec')
      {
          $bulan = '12';
      }
      
      $cleandate = $tahun . "-".$bulan."-".$tanggal." ".$jam;
      return $cleandate;
  }
  
  public function dochangepassword()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
    //   echo $querystring;
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
      }
      else
      {
          
        $usernya = $fromjsondata['user'] ;
        $oldpass = $fromjsondata['oldpass'] ;
        $newpass = $fromjsondata['newpass'] ;
        $newpassconf = $fromjsondata['newpassconf'] ;
        
        $response['result'] = $usernya;
        
        if($newpass <> $newpassconf)
        {
            $response['result'] = "new password mismatch!";
        }
        else
        {
            $querystring = "select operator from operators where operator = '".$usernya."' and `password` = md5('".$oldpass."')";
            $ada = count($this->m_masters->querying($querystring)->result());
            // $response['result'] = $querystring;
            if ($ada < 1)
            {
                $response['result'] = "Wrong Username or Password!";
            }
            else 
            {
                $querystring = "update operators set `password` = md5('".$newpass."') where operator = '".$usernya."' and `password` = md5('".$oldpass."')";
                $this->m_masters->querying($querystring);
                $response['result'] = "password successfully updated!";
                
            }
        }
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  
  public function dochangepassword_bypass()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
    //   echo $querystring;
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
      }
      else
      {
          
        $usernya = $fromjsondata['user'] ;
        $newpass = $fromjsondata['newpass'] ;
        $newpassconf = $fromjsondata['newpassconf'] ;
        
        $response['result'] = $usernya;
        
        if($newpass <> $newpassconf)
        {
            $response['result'] = "new password mismatch!";
        }
        else
        {

                $querystring = "update operators set `password` = md5('".$newpass."'), loggedin = 1 where operator = '".$usernya."'";
                $this->m_masters->querying($querystring);
                $response['result'] = "password successfully updated!";
                // echo $querystring;
            
        }
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  

  
  
  public function doupdateresponse()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {

      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
    //   echo $querystring;
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
      }
      else
      {
          
        $responsenya = $fromjsondata['response'] ;
        $phoneno = $fromjsondata['phoneno'] ;
        $tabledata = $fromjsondata['tabledata'] ;
        $telenya = $fromjsondata['telenya'] ;
        
        $queryresponselist = "select * from responses where response = '".$responsenya."'";
        $responselist = $this->m_masters->querying($queryresponselist)->result();
        
        

        if (count($responselist) < 1)
        {
            $response['result'] = "incorrect response!";
        }
        else
        {
            $querystring = "update work set response = '".$responsenya."', uploaddate = now() where phoneno = '".$phoneno."' and tabledata = '".$tabledata."'" ;
            // echo $querystring;
            $this->m_masters->querying($querystring);
            
            if($telenya == '')
            {
                $querystring = "select creator from work where phoneno = '".$phoneno."' and tabledata = '".$tabledata."'" ;
                $telenya = $this->m_masters->querying($querystring)->result()[0]->creator;
            }
            $querystring = "insert into worktoday values ('".$telenya."','".$phoneno."','".$tabledata."',now())";
            $this->m_masters->querying($querystring);
        
        
            $response['result'] =   "data successfully updated!";
            // echo $querystring;
        }
        
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  public function dorequestphoneno()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
    //   echo $querystring;
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
      }
      else
      {
          
        $userid = $fromjsondata['userid'] ;
        
        // $querychecklogin = "select * from logins where operator = '".$userid."'";
        // $loggedin = $this->m_masters->querying($querychecklogin)->result()[0]->loggedin;
        // //overriding loggedin
        // $loggedin = 1;
        
        $querychecklogin = "select loggedin from operators where operator = '".$userid."'";
        $loggedin = $this->m_masters->querying($querychecklogin)->result()[0]->loggedin;

    //   echo $loggedin;
        
        // $querycounter = "select count(distinct phoneno) as hitung from worktoday where operator = '".$userid."'";
        
        $querycounter = "select count(distinct phoneno) as hitung from work where creator = '".$userid."' and response <> ''";
        $querycountertemp = $this->m_masters->querying($querycounter)->result();
        $dailycounter = $querycountertemp[0]->hitung;
        
        //  echo $querycounter;
        
        $querygetgroup = "select operatorgroup from operators where operator = '".$userid."'";
        $groupnya = $this->m_masters->querying($querygetgroup)->result()[0]->operatorgroup;
        
        // echo $groupnya;
        
        $querymaxcounter = "select IFNULL(sum(maxcall),0) as maxcall from maxcall2 where operatorgroup = '" .$groupnya . "'";
        $maxcounter = $this->m_masters->querying($querymaxcounter)->result()[0]->maxcall;
        $jobleft = $maxcounter - $dailycounter;        
                
        // echo $jobleft;
        
        
        // $querysudahloginhariini = "select * from device where user = '".$userid."'";
        // $sudahloginhariini = count($this->m_masters->querying($querysudahloginhariini)->result());
        
        // if($sudahloginhariini < 1)
        // {
            
        //     $response['result'] = "Mohon relogin dahulu untuk absen hari ini!";
        // }
        
        if($loggedin == 1 || $loggedin == 2)
        {
          $querydatadiri = "select * from agents where user_agent = '".$userid. "'";
          $datadiriexist = $this->m_masters->querying($querydatadiri)->result();
          
          if(count($datadiriexist) < 1)
          {
            $response['result'] = "Mohon Request SPV untuk isi Data Diri Terlebih Dahulu!";
          }
          else if ($jobleft >= 1)
          {
              $queryresponselist = "select * from responses where response <> ''";
                $response['responselist'] = $this->m_masters->querying($queryresponselist)->result();
            
            
                $querystring = "select a.PhoneNo, b.TableData,a.Username as Remarks, a.Creator as UserID, a.CreatorOperatorGroup as Toko from work a inner join tabledatamapping b on a.Tabledata = b.Tabledata 
                        where b.OperatorGroup in ( select operatorgroup from operators where operator = '".$userid."') and response = '' and  a.creator = '".$userid."'  and b.ID <> '0' and b.ID <> 'inactive'
                        

                        
                        order by CAST(b.ID As Unsigned),CAST(a.RunningNo As Unsigned)   limit 1" ;
                        
                $callthis =   $this->m_masters->querying($querystring)->result(); 
                
                
                
                $response['advertisement'][0]->link_adsnya = "";
                $response['advertisement'][0]->beda_waktu = "";
                
                if(count($callthis) >= 1)
                {
                    
                    $response['callthis'] = $callthis;
                   //////////////////////advertisement part////////////////////////////////////
                   
                   
                   $querystring = "select uploaddate from work where response <> '' and creator = '".$userid."' order by uploaddate desc limit 1";
                   $terakhirambil = $this->m_masters->querying($querystring)->result();
                   
                   
                        
                        
                   if(count($terakhirambil) >= 1)
                   {
                      
                     $kapanterakhirambil = $terakhirambil[0]->uploaddate;  
                    
                     $querystring = "select TIME_TO_SEC(TIMEDIFF(now(), '".$kapanterakhirambil."')) as bedawaktu  ";
                     $bedawaktu = $this->m_masters->querying($querystring)->result()[0]->bedawaktu;
                     

                    //  echo $bedawaktu;
                     if($bedawaktu < 30)
                     {
                         
                        // echo "cepet2";
                        $querystring = "select jumlahads from ads_count";
                        $jumlahads = $this->m_masters->querying($querystring)->result()[0]->jumlahads;
                        
                        // echo $jumlahads;
                        $querystring = "select  floor((rand()*(" .$jumlahads . ") + 1)) as acak";
                        $nomorads = $this->m_masters->querying($querystring)->result()[0]->acak;
                        
                        
                        
                        $querystring = "select source_url from ads where id = ".$nomorads;
                        $response['advertisement'][0]->link_adsnya = $this->m_masters->querying($querystring)->result()[0]->source_url;
                        $response['advertisement'][0]->beda_waktu = 30 - $bedawaktu;
                        
                        $querylog = "insert into ads_log values ('".$response['advertisement'][0]->link_adsnya."','".$userid."',now())";
                        $this->m_masters->querying($querylog);
                         
                     }
                   }
                   
                    
                    
                    
                }
                else
                {
                    
                    $response['result'] = "Data tidak diberikan!";
                    
                }
                
          }
          else
          {
            if($maxcounter == 0)
            {
                $response['result'] = "Data tidak diberikan!";
            }
            else
            {
              $response['result'] = "Data sudah ambil maksimum!";
            }
          }
        }
        
        // else if ($loggedin == 3)
        // {
            
        //     $response['result'] = "Mohon Request SPV untuk isi Data Diri Terlebih Dahulu!";
        // }
        
        else
        {
            
            $response['result'] = "Tele sudah tidak aktif! mohon untuk request reaktivasi tele oleh SPV! AKTIFKAN DI JAM 9 malam hingga 3 pagi";
        }
        
        
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  public function dologout()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $userid = $fromjsondata['userid'] ;

        $queryupdatelogin = "update logins set loggedin = '0' where operator = '".$fromjsondata['userid']."'";
		$this->m_masters->querying($queryupdatelogin);
		
		
        $response['result'] =   "User has sucesfully been logged out !";
        // echo $querystring;
        
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  public function dogetagents()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $querystring = "select operator as user_agent, operatorgroup as toko from operators where operatorgroup in (
                		select operatorgroup from operators where operator = '".$fromjsondata['userid']."' and (privilege = 'Supervisor' or privilege = 'Admin')
                	) and privilege = 'tele'";
		$theuser = $this->m_masters->querying($querystring)->result();
		$countofuser = count($theuser);
		
		if($countofuser > 0)
		{
            $response['result'] = $theuser;
		}
		else
		{
		    $response['result'] = "Data Agent tidak ditemukan";
		    
		}
		  
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  public function doupdateagentpassword()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $querystring = "select user, device_id, reset from device where user in (

                select operator from operators where operatorgroup in (
                		select operatorgroup from operators where operator = '".$fromjsondata['userid']."' and (privilege = 'Supervisor' or privilege = 'Admin')
                	) and privilege = 'tele'
                ) and user = '".$fromjsondata['resetpass_userid']."'";
		$theuser = $this->m_masters->querying($querystring)->result();
		$countofuser = count($theuser);
		
		if($countofuser > 0)
		{

			$usernya = $fromjsondata['resetpass_userid'] ;
            $newpass = $fromjsondata['newpass'] ;
            $newpassconf = $fromjsondata['newpassconf'] ;
            
            $response['result'] = $usernya;
            
            if($newpass <> $newpassconf)
            {
                $response['result'] = "new password mismatch!";
            }
            else
            {
    
                    $querystring = "update operators set `password` = md5('".$newpass."'), loggedin = 2 where operator = '".$usernya."'";
                    $this->m_masters->querying($querystring);
                    $response['result'] = "password successfully updated!";
                    // echo $querystring;
                
            }
		}
		else
		{
		    $response['result'] = "Data Agent tidak ditemukan";
		    
		}
		  
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  public function dogetconsumption()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $querystring = "select creator as tele, creatoroperatorgroup as `group`, count(1) as konsumsi_data from (
            select * from work where  creatoroperatorgroup in (select operatorgroup from operators where operator = '".$fromjsondata['userid']."') and response <> '' 
            and date(uploaddate) >= date('" .$fromjsondata['start_date']."') and date(uploaddate) <= date('" .$fromjsondata['end_date']."')  union all
            
            select * from workstorage where  creatoroperatorgroup in (select operatorgroup from operators where operator = '".$fromjsondata['userid']."') and response <> '' 
            and date(uploaddate) >= date('" .$fromjsondata['start_date']."') and date(uploaddate) <= date('" .$fromjsondata['end_date']."')
            )a group by creator, creatoroperatorgroup order by count(1) desc, creatoroperatorgroup, creator";
		$theuser = $this->m_masters->querying($querystring)->result();
		$countofuser = count($theuser);
		
		if($countofuser > 0)
		{
			$response['result'] = $theuser; 
			
		}
		else
		{
		    
		    $response['result'] = "Data Konsumsi tidak ditemukan";
		}
		  
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  public function doupdatedevices()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $querystring = "select user, device_id, reset from device where user in (

                select operator from operators where operatorgroup in (
                		select operatorgroup from operators where operator = '".$fromjsondata['userid']."' and (privilege = 'Supervisor' or privilege = 'Admin')
                	) and privilege = 'tele'
                ) and user = '".$fromjsondata['reset_userid']."'";
		$theuser = $this->m_masters->querying($querystring)->result();
		$countofuser = count($theuser);
		
		if($countofuser > 0)
		{

			$queryreset = "update device set reset = '1' where user = '".$fromjsondata['reset_userid']."' ";
			$this->m_masters->querying($queryreset);
			$response['result'] = "Device berhasil direset";
		}
		else
		{
		    $response['result'] = "Data Device tidak ditemukan";
		    
		}
		  
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  
  public function dogetdevices()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $querystring = "select user, device_id, reset from device where user in (

                select operator from operators where operatorgroup in (
                		select operatorgroup from operators where operator = '".$fromjsondata['userid']."' and (privilege = 'Supervisor' or privilege = 'Admin')
                	) and privilege = 'tele'
                )";
		$theuser = $this->m_masters->querying($querystring)->result();
		$countofuser = count($theuser);
		
		if($countofuser > 0)
		{
			$response['result'] = $theuser; 
			
		}
		else
		{
		    
		    $response['result'] = "Data Device tidak ditemukan";
		}
		  
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  public function dologin()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();
      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $querystring = "select * from operators where operator = '".$fromjsondata['userid'] . "' and password = md5('".$fromjsondata['password'] . "') and loggedin in ('1','2')";
		$theuser = $this->m_masters->querying($querystring)->result();
		$countofuser = count($theuser);
		
		if($countofuser > 0)
		{
			$operatorgroup = $theuser[0]->OperatorGroup;
		    $querystring = "select gsecret from gsecret where operatorgroup ='".$operatorgroup."'";
		    $secret = $this->m_masters->querying($querystring)->result()[0]->gsecret;
		    
		    $g = new \Sonata\GoogleAuthenticator\GoogleAuthenticator();

		
		    
		  //  if ($g->checkCode($secret, $fromjsondata['gcode'])) 
		  //  {
		      //  $queryupdatelogin = "update operators set loggedin = '1' where operator = '".$fromjsondata['userid']."'";
		      //  $this->m_masters->querying($queryupdatelogin);
		        
		        $loggedin = $theuser[0]->loggedin;

		        $response['result']['message'] = "You Are Welcomed!";
		        $response['result']['firsttime_flag'] = $loggedin;
		  //  }
		  //  else
		  //  {

		  //      $response['result']['message'] = "Failed Google Authenticator !";
		  //      $response['result']['firsttime_flag'] = "";
		  //  }
			
		}
		else
		{
		    $querystring = "select * from operators where operator = '".$fromjsondata['userid'] . "'";
				    $loggedin = $this->m_masters->querying($querystring)->result()[0]->loggedin;
			
			if($loggedin == "0")
		    {
		        $response['result']['message'] = "Tele tidak aktif";
		        $response['result']['firsttime_flag'] = "";
		    }
		    else if ($loggedin == "")
		    {

		        
		        $response['result']['message'] = "Tele tidak ditemukan";
		        $response['result']['firsttime_flag'] = "";
		
		    }
		    else
		    {
		        $response['result']['message'] = "Password salah";
		        $response['result']['firsttime_flag'] = "";
		        
		    } 	    
				    
		    
		}  
        
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  public function dogetname()
  {
      
    //   echo "asdf";
    $fromjsondata = (array)json_decode(file_get_contents('php://input'));
    $this->form_validation->set_data($fromjsondata);
    $this->form_validation->set_rules('apipassword', 'apipassword', 'required|xss_clean');
    
    if ($this->form_validation->run() == FALSE)
    {
        // print_r($fromjsondata);
      $response['Info'] = validation_errors();
      $this->output
      ->set_status_header(400)
      ->set_content_type('application/json', 'utf-8')
      ->set_output(json_encode($response, JSON_PRETTY_PRINT))
      ->_display();
      exit;
    }
    else
    {
        // echo "asdf";
      $querystring = "select * from authenticator_feeding where `password` = '".$fromjsondata['apipassword']. "'";
      $authentication = $this->m_masters->querying($querystring)->result();

      if (count($authentication) < 1)
      {
          $response['result'] = "wrong api password";
          
          
      }
      else
      {
          
        $querygetname = "call getname();";
		$response['result'] = $this->m_masters->querying($querygetname)->result();
        $this->db->close();
// 		$countofuser = count($thename);
        // print_r($thename);
      }
      $this->output
          ->set_status_header(200)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  
  
}