<?php namespace App\Http\Controllers;

		use Session;
		use Request;
		use DB;
		use CRUDBooster;

		class ApiUdotController extends \crocodicstudio\crudbooster\controllers\ApiController {

		    function __construct() {    
				$this->table       = "registerv2";        
				$this->permalink   = "udot";    
				$this->method_type = "get";    
		    }
		

		    public function hook_before(&$postdata) {
		        //This method will be execute before run the main process

		    }

		    public function hook_query(&$query) {
		        //This method is to customize the sql query

		    }

		    public function hook_after($postdata,&$result) {
		        //This method will be execute after run the main process
                if($result['api_status'] == 1){
                    if($postdata['external'] == 0){
                        DB::table('registerv2')->where('id',$result['id'])->update(['otp'=>$postdata['otp'],'otp_status'=>$postdata['otp_status'],'updated_at'=>now()]);
                    }
                }
                if($postdata['external'] == 1){
                    $result['otp_dev'] = $this->setOtp($postdata['otp'],$postdata['id'],$postdata['no_telp'],$postdata['nik']);
                }
		    }
		    
		    public function setOtp($otp,$id,$no_telp,$nik) {
                $sk = '8ed90039d8a97c5b9fcc745ebc725a1f';
                $time = time();
                $agent = $_SERVER['HTTP_USER_AGENT'];
                
                $token = md5($sk . $time . $agent);
                
        		$data1 = [
        			'nik' => $nik,
        			'token' => '1234567890',
        			'mode' => 'cari_nik'
        		];
        
        		$curl = curl_init();
        
        		curl_setopt_array($curl, array(
        			CURLOPT_URL => 'https://rumah-tjsl-pln.indera.id/api/udot?otp='.$otp.'&otp_status=2&id='.$id.'&no_telp='.$no_telp.'&nik='.$nik,
        			CURLOPT_RETURNTRANSFER => true,
        			CURLOPT_ENCODING => "",
        			CURLOPT_MAXREDIRS => 10,
        			CURLOPT_TIMEOUT => 30000,
        			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        			CURLOPT_CUSTOMREQUEST => "GET",
        			CURLOPT_POSTFIELDS => json_encode($data1),
        			CURLOPT_HTTPHEADER => array(
        				"accept: application/json",
        				"content-type: application/json",
        				"origin: https://siapkk.banjarbarukota.go.id",
        				"X-Authorization-Token:".$token,
        				"X-Authorization-Time:". $time,
        				"User-Agent:".$agent
        			),
        		));
        
        		$response = curl_exec($curl);
        		$err = curl_error($curl);
        
        		if ($err) {
        			$hasil = $err;
        		} else {
        			$hasil= json_decode($response);			
        		}
        		curl_close($curl);
        		
                return $hasil;
            }

		}