<?php namespace App\Http\Controllers;

		use Session;
		use Request;
		use DB;
		use CRUDBooster;
		use DateTime;
		use DateInterval;

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

		    function __construct() {    
				$this->table       = "waconv";        
				$this->permalink   = "req_link";    
				$this->method_type = "post";    
		    }
		

		    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){
                    $rand = $this->generateRandomString(6);
                    $exist = DB::table('bahandap')->where('kunci',$rand)->first();
                    while($exist){
                        $rand = $this->generateRandomString(6);
                    }
                    //$result['rand'] = $rand;
                    //$result['time_add'] = $now->add(new DateInterval('PT1H'));
                    $result['uk']=$result['cms_users_id'];
                    if(strlen($result['cms_users_id'])==0){
                        $result['bahandap'] = 'Oo tidak..';
                    }else{
                        $now = new DateTime();
                        $now->add(new DateInterval('PT1M'));
                        $result['unused'] = $now->format('Y-m-d H:i:s');
                        DB::table('bahandap')->insert([
                                'kunci' => $rand,
                                'owner' => $result['cms_users_id'],
                                'redurl' => 'https://peta-covid.banjarbarukota.go.id?kunci='.$rand,
                                'updated_by' => $result['cms_users_id'],
                                'gen' => 1,
                                'expired_at' => $now->format('Y-m-d H:i:s')
                            ]);  
                        $result['bahandap'] = 'Silahkan ikuti link berikut https://bjb.city/'.$rand;
                    }
		        }else{
		            $result['bahandap'] = 'Oo tidak..';
		        }
		    }
		    
		    public function generateRandomString($length = 10) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $charactersLength = strlen($characters);
                $randomString = '';
                for ($i = 0; $i < $length; $i++) {
                    $randomString .= $characters[rand(0, $charactersLength - 1)];
                }
                return $randomString;
            }

		}