<?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 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'] ;
        
        $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."'" ;
            $this->m_masters->querying($querystring);
            $response['result'] =   "data successfully updated!";
            // echo $querystring;
            
            $querystring = "select creator from work where phoneno = '".$phoneno."' and tabledata = '".$tabledata."'" ;
            $userid = $this->m_masters->querying($querystring)->result()[0]->creator;
            
            $querystring = "insert into worktoday values ('".$userid."','".$phoneno."','".$tabledata."',now())";
        $this->m_masters->querying($querystring);
        }
        
        
      }
      $this->output
          ->set_status_header(400)
          ->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;
        
        $querygroup = "select * from operators where operator = '".$userid."'";
        $group  = $this->m_masters->querying($querygroup)->result()[0]->OperatorGroup;
        // echo $querygroup;

        if($loggedin == 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'
                    and dayname(now())<>'SUNDAY'
                    and
                    hour(now()) >= 10
                    and
                    hour(now()) <= 22

                    order by CAST(b.ID As Unsigned),CAST(a.RunningNo As Unsigned)   limit 1" ;
            $response['callthis'] =   $this->m_masters->querying($querystring)->result(); 
            // $panggil = $this->m_masters->querying($querystring)->result(); 
            // echo $querystring;
            
            $querycounter = "select count(distinct phoneno) as hitung from worktoday where operator = '".$userid."'";
                $querycountertemp = $this->m_masters->querying($querycounter)->result();
                $dailycounter = $querycountertemp[0]->hitung;
                
            // echo $querycounter;
                
            $querymaxcounter = "select maxcall from maxcall2 where operatorgroup = '" .$group . "'";
                $maxcounter = $this->m_masters->querying($querymaxcounter)->result()[0]->maxcall;
    
                $jobleft = $maxcounter - $dailycounter;
                
                // echo $jobleft;
            $jumlahcall = count($response['callthis']);
            if($jumlahcall == 0 || $jobleft < 1 ||  date('D', mktime(0, 0, 0, date("m"), date("d")-21, date("Y"))) == 'Sun' ) 
                { 
                // if($data['listscounts'] == 0 ) 
                // { 
                    $response['error'] = '<div class="alert alert-info alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                            <h5><i class="icon fas fa-info"></i> Info!</h5>
                            There is no more work to be done!
                          </div>' ;
            
                }

            
        }
        
        else
        {
            
            $response['result'] = "User has to login first!";
        }
        
        
        
      }
      $this->output
          ->set_status_header(400)
          ->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(400)
          ->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'] . "')";
		$theuser = $this->m_masters->querying($querystring)->result();
		$countofuser = count($theuser);
		
// 		echo $querystring;
		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 logins set loggedin = '1' where operator = '".$fromjsondata['userid']."'";
		        $this->m_masters->querying($queryupdatelogin);
		        
		      //  echo $queryupdatelogin;
		        $response['result'] = "You Are Welcomed!";
		    }
		    else
		    {
		        $response['result'] = "Failed Google Authenticator !";
		    }
			
		}
		else
		{
		    $response['result'] = "Invalid Username And Password!";
		}  
        
      }
      $this->output
          ->set_status_header(400)
          ->set_content_type('application/json', 'utf-8')
          ->set_output(json_encode($response, JSON_PRETTY_PRINT))
          ->_display();
          exit;
    }
  }
  
  
  
}