<?php namespace App\Http\Controllers;

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

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

		    function __construct() {    
				$this->table       = "warga_bjb";        
				$this->permalink   = "dafar_silkahi";    
				$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) {
				$telp_exist = DB::table('cms_users')->where('no_telp',$postdata['telp'])->first();
				if(!$telp_exist){
					$nik_exist = DB::table('warga_bjb')->where('nik',$postdata['nik'])->first();
					if($nik_exist){
						similar_text($nik_exist->nama_lgkp,strtoupper($postdata['name']),$similar);
						if( $similar >= 90 ){
							$user_exist = DB::table('cms_users')->where('nik',$postdata['nik'])->first();
							if($user_exist){
								$result['sudah terdaftar'] = 1;
								$result['api_status']=1;
								$result['api_message']="NIK Sudah Terdaftar !";
							}else{
							    if($postdata){
    								$pass = random_int(100000, 999999);
    								DB::table('cms_users')->insert([
    									'nik'=>$postdata['nik'],
    									'name'=>strtoupper($postdata['name']),
    									'display_name'=>strtoupper($postdata['name']),
    									'no_telp'=>$postdata['telp'],
    									'password'=>\Hash::make($pass),
    									'status'=>'Active'
    								]);
    								$result['pass'] = $pass;
    								$result['api_status']=1;
    								$result['api_message']="Pendaftaran berhasil, \nNIK : " . $postdata['nik'] . "\nPassword : " . $pass;
							    }
							}
						}else{
							$result['api_status']=0;
							$result['api_message']="Data Tidak Sesuai ! " . $similar;
						}
						
					}else{
					    if($postdata){
    						$pass = random_int(100000, 999999);
    						DB::table('warga_bjb')->insert([
    							'nik'=>$postdata['nik'],
    							'nama_lgkp'=>strtoupper($postdata['name']),
    							'telp'=>$postdata['telp']
    						]);
    						DB::table('cms_users')->insert([
    							'nik'=>$postdata['nik'],
    							'name'=>strtoupper($postdata['name']),
    							'display_name'=>strtoupper($postdata['name']),
    							'no_telp'=>$postdata['telp'],
    							'password'=>\Hash::make($pass),
    							'status'=>'Active'
    						]);
    						$result['pass'] = $pass;
    						$result['api_status']=1;
    						$result['api_message']="Pendaftaran berhasil, \nNIK : " . $postdata['nik'] . "\nPassword : " . $pass;
					    }
					}
				}else{
					$result['api_status']=0;
					$result['api_message']="Nomor Telepon Sudah Pernah Digunakan ! ";
				}
		    }

		}