<?php namespace App\Http\Controllers;

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

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

		    function __construct() {    
				$this->table       = "waconv";        
				$this->permalink   = "req_custom_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){
		            $attemp=DB::table('bahandap')->where('conv_id',$result['id'])->get();
		            $putih=DB::table('daftar_putih')->where('konteks','1login')->where('conv_id',$result['id'])->first();
		            if(sizeof($attemp)>=3 && $result['id'] != $putih->conv_id){
		                $result['bahandap'] = 'Mohon maaf, anda tidak diperkenankan melakukan registrasi lagi.';
		            }else{
                        $rand = $this->generateRandomString($postdata['panjang']);
                        $exist = DB::table('bahandap')->where('kunci',$rand)->first();
                        while($exist){
                            $rand = $this->generateRandomString($postdata['panjang']);
                        }
       
                        $now = new DateTime();
                        $now->add(new DateInterval('PT3M'));
                        $result['unused'] = $now->format('Y-m-d H:i:s');
                        DB::table('bahandap')->insert([
                                'kunci' => $rand,
                                'owner' => $result['cms_users_id'],
                                'redurl' => $postdata['redurl']. '/'.$rand,
                                'hit_limit' => 9,
                                'conv_id' => $result['id'],
                                'gen' => 1,
                                'updated_by' => 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;
            }

		}