<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class ParkingController extends Controller
{
	
    public function users()
    {
    
		$data = DB::table("parking_in")->selectRaw("now() AS waktu_keluar")->first();
				dd(($data->waktu_keluar));
    }
	
	public function info($id){
		return $id;
	}
	
	public function img_list($id){
		//425461671666PM945
		$site = substr($id,0,3);
		$data = DB::table("parking_in")
		->where("site_id",$site)
		->where("ti_qrcode",substr($id,3,17))
		->select("ti_img")
		->first();
		
		
		return $data->ti_img;
		/*
		$img = explode("|",$data->ti_img);
		$c = count($img);
		for($i=0;$i<$c;$i++){
			//echo "<img src='".assets('storage/parking_image')."/".$img[$i]."' alt='' title='' />";
		}
		*/
	}
	function getAuthorizationHeader(){
        $headers = null;
        if (isset($_SERVER['Authorization'])) {
            $headers = trim($_SERVER["Authorization"]);
        }
        else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
            $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
        } elseif (function_exists('apache_request_headers')) {
            $requestHeaders = apache_request_headers();
            // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
            $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
            //print_r($requestHeaders);
            if (isset($requestHeaders['Authorization'])) {
                $headers = trim($requestHeaders['Authorization']);
            }
        }
        return $headers;
    }
	
	function getBearerToken_old() {
		$headers = $this->getAuthorizationHeader();
		// HEADER: Get the access token from the header
		if (!empty($headers)) {
			if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
				return $matches[1];
			}
		}
		return null;
	}
	
	function getBearerToken() {
		$token = "1234567890123";
		$rs = "";
		$headers = $this->getAuthorizationHeader();
		// HEADER: Get the access token from the header
		if (!empty($headers)) {
			if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
				$rs =  $matches[1];
			}
		}
		if($rs == $token){
			return true;
		}
		return null;
	}
	
	function doLogin(Request $request){
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'site_id'   => 'required',
				'user_id' => 'required',
				'device_id' => 'required',
				'lobby_id' => 'required',
				'passwd' => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid login parameter!',
					'data'   => $validator->errors()
				],200);

			} else {

				$data = DB::table("master_user")
				->where("site_id",$request->site_id)
				->where("userid",$request->user_id)
				->where("pwd",md5($request->passwd))
				->select("fullname","ustatus","device_id")
				->selectRAW("LPAD(FLOOR(RAND() * 999999.99), 6, '0') as shift_id")
				->get()->first();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Invalid login',
						'data'    => null
						], 200);
				}
				else{
					$d_device_id = $data->device_id;
					$d_login_status = $data->ustatus;
					
					if($d_login_status == 'S' and $d_device_id != $request->device_id){
						return response()->json([
						'success' => false,
						'message' =>'User is active on another device!',
						'data'    => ''
						], 200);
					}
					else{
						
						$now = date('Y-m-d H:i:s');
						
						if($d_login_status == "E"){
							DB::table("master_user")
							->where("site_id",$request->site_id)
							->where("userid",$request->user_id)
							->update([
							"ustatus"=>"S",
							"device_id"=>$request->device_id,
							"lobby_id"=>$request->lobby_id,
							"startshift"=>$now,
							"shift_id"=>$data->shift_id
							]);
						}
						
						
						return response()->json([
						'success' => true,
						'message' =>'Login success',
						'data'    => $data
						], 200);
					}
					
				}
			}
		}
	}
	
	function cekDevice(Request $request){
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'site_id'   => 'required',
				'device_id' => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid request parameter!',
					'data'   => $validator->errors()
				],200);

			} else {
				
				DB::table("master_device")
				->insert(["site_id"=>$request->site_id,"device_id"=>$request->device_id]);
				
			
				//select a.siteid, a.sitename, b.device_id from master_site a 
				//left join master_device b on a.siteid = b.site_id 
				$data = DB::table("master_device")
				->leftJoin("master_device","master_site.siteid","=","master_device.site_id")
				->where("site_id",$request->site_id)
				->where("device_id",$request->device_id)
				->select("master_site.siteid as site_id","master_site.sitename as site_name","master_device.device_id")
				->get()->first();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Device not registered',
						'data'    => null
						], 200);
				}
				else{
					return response()->json([
						'success' => true,
						'message' =>'Device cek success',
						'data'    => $data
						], 200);
				}
			}
		}
	}
	
	function doLogout(Request $request){
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'site_id'   => 'required',
				'user_id' => 'required',
				'device_id' => 'required'
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid logout parameter!',
					'data'   => $validator->errors()
				],200);

			} else {
					
					//settlement
					if($request->site_id == "LOP"){
						$now = date('Y-m-d H:i:s', strtotime('now +1 hour'));
					}
					else{
						$now = date('Y-m-d H:i:s');
					}
					
					$data = DB::table("users")
					->where("site_id",$request->site_id)
					->where("userid",$request->user_id)
					->where("device_id",$request->device_id)->first();
					
					
					DB::table("users")
					->where("site_id",$request->site_id)
					->where("siteid",$request->user_id)
					->where("device_id",$request->device_id)
					->update(["ustatus"=>"E","endshift"=>$now]);
					
					$sql = 
					"select users.userid,  users.shift_id,  users.fullname fullname, device_id gateout, COUNT(*) AS qty, SUM(parking_fee) AS casual, 
					SUM(CASE WHEN lt_fee > 0 THEN 1 ELSE 0 END) AS qty_lt,
					SUM(CASE WHEN payment_type > 0 THEN 1 ELSE 0 END) AS prepaid_qty,
					SUM(CASE WHEN payment_type > 0 THEN parking_fee ELSE 0 END) AS prepaid_amount,
					SUM(CASE WHEN lt_fee > 0 THEN lt_fee ELSE 0 END) AS amount_lt,
					SUM(CASE WHEN userin = 'MANUAL' THEN 1 ELSE 0 END) AS qty_manual,
					SUM(CASE WHEN userin = 'MANUAL' THEN parking_fee ELSE 0 END) AS amount_manual, 
					DATE_FORMAT(users.startshift,'%Y-%m-%d %H:%i:%s') startshift, 
					DATE_FORMAT(users.endshift,'%Y-%m-%d %H:%i:%s') endshift
					FROM parking_out_mobile right join users on parking_out_mobile.userout = users.userid 
					where parking_out_mobile.shift_id = '".$data->shift_id."'
					AND users.ustatus = 'E'  and users.userid='".$data->userid."' group by users.userid,
					users.fullname, parking_out_mobile.device_id, users.startshift, users.endshift, users.shift_id";
					
						$data = DB::select(DB::RAW($sql));
						
						//dd($data);
						foreach($data as $rs){
							$gate = $rs->gateout;
							$username = $rs->fullname;
							$userid = $rs->userid;
							$start_shift = $rs->startshift;
							$end_shift = $rs->endshift;
							$casual_amount = $rs->casual;
							$casual_qty =$rs->qty;
							$lt_amount = $rs->amount_lt;
							$lt_qty = $rs->qty_lt;  //$rs->qty_lt;
							$manual_amount = $rs->amount_manual;  //$rs->amount_manual;
							$manual_qty = $rs->qty_manual;  //$rs->qty_manual;
							$prepaid_qty = $rs->prepaid_qty;  //$rs->prepaid_qty;
							$prepaid_amount = $rs->prepaid_amount;
							$shift_id = $rs->shift_id;
		//insert into settlement (userid, gate, start_shift, end_shift, casual_amount, casual_qty,"
		//        + "lt_amount, lt_qty, manual_amount, manual_qty, shift_id, prepaid_qty,prepaid_amount) values ("
		//        + "'" + userid + "','" + gate + "','" + start_shift + "','" + end_shift + "','" + casual_amount + "','" + casual_qty + "',"
		//       + "'" + lt_amount + "','" + lt_qty + "','" + manual_amount + "','" + manual_qty + "','" + shift_id + "','" + prepaid_qty + "','" + prepaid_amount + "')
							 DB::table("settlement")
							 ->insert([
								"userid"=>$userid,
								"gate"=>$gate,
								"start_shift"=>$start_shift,
								"end_shift"=>$end_shift,
								"casual_amount"=>$casual_amount,
								"casual_qty"=>$casual_qty,
								"lt_amount"=>$lt_amount,
								"lt_qty"=>$lt_qty,
								"manual_amount"=>$manual_amount,
								"manual_qty"=>$manual_qty,
								"shift_id"=>$shift_id,
								"prepaid_qty"=>$prepaid_qty,
								"prepaid_amount"=>$prepaid_amount
							 ]);
						}
			
			
					
					return response()->json([
						'success' => true,
						'message' =>'Logout success',
						'data'    => null
						], 200);
			}
		}
	}
	
	
	public function master_vehicle(Request $request)
    {
		if($this->getBearerToken()  ==  false){
			//$this->response(array("code"=>2,"message"=>"Invalid credential")); 
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else{
			$validator = Validator::make($request->all(), [
				'site_id' => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {

				$data = DB::table("casualcharges")
				->where("site_id",$request->site_id)
				->select("id as vehicle_code","vehicle_name","site_id")
				->get();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Data not found',
						'data' => ''
						], 201);
				}
				else{
					return response()->json([
						'success' => true,
						'message' => null,
						'data' => $data
						], 200);
				}
			}
		}
    }
	
	public function master_lobby(Request $request)
    {
		if($this->getBearerToken()  ==  false){
			//$this->response(array("code"=>2,"message"=>"Invalid credential")); 
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else{
			$validator = Validator::make($request->all(), [
				'site_id' => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {

				$data = DB::table("master_lobby")
				->where("site_id",$request->site_id)
				->get();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Data not found',
						'data' => ''
						], 201);
				}
				else{
					return response()->json([
						'success' => true,
						'message' => null,
						'data' => $data
						], 200);
				}
			}
		}
    }
	
	public function cek_device(Request $request)
    {
		if($this->getBearerToken()  ==  false){
			//$this->response(array("code"=>2,"message"=>"Invalid credential")); 
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else{
			$validator = Validator::make($request->all(), [
				'site_id' => 'required',
				'device_id' => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {

				$data = DB::table("master_device")
				->leftJoin("master_site","master_site.siteid","=","master_device.site_id")
				->where("site_id",$request->site_id)
				->where("device_id",$request->device_id)
				->select("master_site.siteid as site_id","master_site.sitename as site_name","master_device.device_id")
				->get()->first();
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Device not found',
						'data' => ''
						], 201);
				}
				else{
					return response()->json([
						'success' => true,
						'message' => null,
						'data' => $data
						], 200);
				}
			}
		}
    }
	
	
	function requestParkingRate(Request $request){
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'ticket_no'   => 'required',
				//'vehicle_code' => 'required',
				'site_id' => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {
				if ($request->ticket_no == '123') {

					return response()->json([
						'success' => false,
						'message' => 'Invalid ticket number!',
						'data'   => $validator->errors()
					],200);

				}
				
			
				$now = date('Y-m-d H:i:s');
				
				
				$data = DB::table("parking_in")
				->where("ti_qrcode",$request->ticket_no)
				->where("site_id",$request->site_id)
				->selectRaw("ti_key, ti_policeno, ti_vehicle, DATE_FORMAT(ti_datetime,'%d %b %Y %H:%i:%s') as parking_datetimein, 
                            DATE_FORMAT('$now','%d %b %Y %H:%i:%s') as waktu_keluar, CEIL(TIMESTAMPDIFF(SECOND, ti_datetime, 
							'$now')/60) as durasi, DAYOFWEEK(ti_datetime) as hari")
				->get()->first();
				//dd($data);
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Data not found',
						'parking_fee'    => null,
						'durasi1'    => "",
						'durasi2'    => "",
						'datetimein'    => "",
						'datetimeout'    => null,
						], 200);
				}
				else{
					return response()->json([
						'success' => true,
						'message' => null,
						'durasi1' => $data->durasi,
						'durasi2' => $this->konversi($data->durasi),
						'datetimein'    => $data->parking_datetimein,
						'datetimeout' => $data->waktu_keluar,
						'policeno' => $data->ti_policeno,
						'parking_fee'    => $this->hitung($data->ti_vehicle,$data->durasi,0,$request->site_id)
						], 200);
				}
			}
		}
	}
	
	function requestParkingRateManual(Request $request){
		
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'datetimein'   => 'required', //format dd-mm-yyyy HH:mm
				'vehicle_code' => 'required',
				'site_id' => 'required',
				'isLT' => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {
				if($request->site_id == "LOP"){
					$now = date('Y-m-d H:i:s', strtotime('now +1 hour'));
				}
				else{
					$now = date('Y-m-d H:i:s');
				}
				$data = DB::table("parking_in")
				->selectRaw("DATE_FORMAT(STR_TO_DATE('" .$request->datetimein. ":00','%d-%m-%Y %H:%i:%s'),'%Y-%m-%d %H:%i:%s') AS parking_datetimein, 
				'$now' AS waktu_keluar, ceil(TIMESTAMPDIFF(SECOND, STR_TO_DATE('" .$request->datetimein. ":00','%d-%m-%Y %H:%i:%s'), 
				'$now')/60) AS durasi, DAYOFWEEK(STR_TO_DATE('" .$request->datetimein. ":00','%d-%m-%Y %H:%i:%s')) as hari")->first();
				//dd($data);
				return response()->json([
						'success' => true,
						'message' => null,
						'durasi1' => $data->durasi,
						'durasi2' => $this->konversi($data->durasi),
						'datetimein' => $request->datetimein,
						'datetimeout' => $data->waktu_keluar,
						'lt' =>$request->isLT,
						'parking_fee'    => $this->hitung($request->vehicle_code,$data->durasi,$request->isLT, $request->site_id)
						], 200);
				
			}
		}
	}
	
	
	
	private function cekHari($site)
    {
		
		$nama_hari = date('l', strtotime(date('Y-m-d')));
		$now = date('Y-m-d');
		
				
				
            
		$cek = DB::table("harilibur")
		->select(DB::raw(" count(*) as cnt "))
		->whereRaw("tanggal = DATE_FORMAT(NOW(),'%Y-%m-%d')")
		->first();
			
		$ceklibur = $cek->cnt;
			

        if($ceklibur > 0)
        {
            $hasil = "Y";
        }
        else
        {
             $hasil = "N";
        }
        return $hasil;
    }
		
	private function hitung($kendaraan, $durasi, $isLT, $site)
    {
		//dd($this->cekHari($site));
		$jam = $durasi;
        if ($this->cekHari($site) == "Y")
        {
            $rstarif = DB::table("casualcharges")     
			->where("hari","H")
			->where("site_id",$site)
			->where("vehicle_name",$kendaraan)
			->whereRaw(" startdate <= NOW()")
			->first();
            
			if($rstarif != null){
				
			
                $charge_type = $rstarif->charge_type;
                $group1_unit = $rstarif->group1_unit;
                $group1_charge = $rstarif->group1_charge;
                $group2_unit = $rstarif->group2_unit;
                $group2_charge = $rstarif->group2_charge;
                $group3_unit = $rstarif->group3_unit;
                $group3_charge = $rstarif->group3_charge;
                $overnight_use = $rstarif->overnight_use;
                $overnight_charge = $rstarif->overnight_charge;
                $overnight_type = $rstarif->overnight_type;
                $overnight_unit = $rstarif->overnight_unit;
                $lt_charge = $rstarif->lt_charge;
                $maxcharge = $rstarif->maxcharge;
                $toleransi = $rstarif->tolerance;
            }

            else
            {
				 $rstarif = DB::table("casualcharges")     
				->where("hari","W")
				->where("site_id",$site)
				->where("vehicle_name",$kendaraan)
				->whereRaw(" startdate <= NOW()")
				->orderBY("startdate","DESC")
				->first();
				
				if($rstarif != null)
				{
					$charge_type = $rstarif->charge_type;
					$group1_unit = $rstarif->group1_unit;
					$group1_charge = $rstarif->group1_charge;
					$group2_unit = $rstarif->group2_unit;
					$group2_charge = $rstarif->group2_charge;
					$group3_unit = $rstarif->group3_unit;
					$group3_charge = $rstarif->group3_charge;
					$overnight_use = $rstarif->overnight_use;
					$overnight_charge = $rstarif->overnight_charge;
					$overnight_type = $rstarif->overnight_type;
					$overnight_unit = $rstarif->overnight_unit;
					$lt_charge = $rstarif->lt_charge;
					$maxcharge = $rstarif->maxcharge;
					$toleransi = $rstarif->tolerance;
				}
                       
                else{
					 $charge_type = "X";
					$group1_unit = 0;
					$group1_charge = 0;
					$group2_unit = 0;
					$group2_charge = 0;
					$group3_unit = 0;
					$group3_charge = 0;
					$overnight_use = "N";
					$overnight_charge = 0;
					$overnight_type = "P";
					$overnight_unit = 0;
					$lt_charge = 0;
					$maxcharge = 0;
					$toleransi = 0;
				}
                   
            }
		}
		else{
			//jika bukan hari libur
			
			$rstarif = DB::table("casualcharges")     
				->where("vehicle_name",$kendaraan)
				->where("site_id",$site)
				->whereRaw(" startdate <= NOW()")
				->orderBY("startdate","DESC")
				->first();
			//dd($rstarif);
				if($rstarif != null)
				{
					$charge_type = $rstarif->charge_type;
					$group1_unit = $rstarif->group1_unit;
					$group1_charge = $rstarif->group1_charge;
					$group2_unit = $rstarif->group2_unit;
					$group2_charge = $rstarif->group2_charge;
					$group3_unit = $rstarif->group3_unit;
					$group3_charge = $rstarif->group3_charge;
					$overnight_use = $rstarif->overnight_use;
					$overnight_charge = $rstarif->overnight_charge;
					$overnight_type = $rstarif->overnight_type;
					$overnight_unit = $rstarif->overnight_unit;
					$lt_charge = $rstarif->lt_charge;
					$maxcharge = $rstarif->maxcharge;
					$toleransi = $rstarif->tolerance;
				}
                       
                else{
					$charge_type = "X";
					$group1_unit = 0;
					$group1_charge = 0;
					$group2_unit = 0;
					$group2_charge = 0;
					$group3_unit = 0;
					$group3_charge = 0;
					$overnight_use = "N";
					$overnight_charge = 0;
					$overnight_type = "P";
					$overnight_unit = 0;
					$lt_charge = 0;
					$maxcharge = 0;
					$toleransi = 0;
				}
                  
		}
        
            //mulai hitung tarif
        if ($toleransi > 0)
        {
            $tol = 1;
        }
        else
        {
            $tol = 0;
        }
        if ($charge_type == "F")
        {
            if ($isLT == 1)
            {
                if ($tol == 1 && ($durasi <= $toleransi))
				{
                    $biayaparkir = $group1_charge;
                }
                else
                {
                   //$biayaparkir = $group1_charge + $lt_charge;
                    $biayaparkir = $group1_charge;
                }
            }
            else
            {
                if ($tol == 1 && ($durasi <= $toleransi))
                {
                    $biayaparkir = 0;
                }
                else
                {
                    $biayaparkir = $group1_charge;
                }
            }
        }
        else if ($charge_type == "X")
        {
            $biayaparkir = 123456789;
        }
        else
        {
            $biayaparkir = 0;
            if ($tol == 1 && ($durasi <= $toleransi))
            {
                if ($toleransi_maks == 0)
                {
                    $biayaparkir = 0;
                }

            }
            else
            {
                   //looping maksimal perhari

                while ($durasi > 0) //28880
                {


                    $tarif1 = $group1_charge;//5000
					//tarif jam pertama = 5000
                    $jam_kedua = ($durasi - $group1_unit); //90 - 60 = 30
					//jam kedua = 90 menit - 60 menit = 30 menit (jam kedua)
                    if ($jam_kedua < 1)
                    {
                        $biayaparkir_maks = $tarif1; //1000
                        $durasi = 0;
                    }
                    else
                    {
                        $tarif2 = $group2_charge; //1000
						//tarif jam kedua = 1000
                        $jam_ketiga = (floor($jam_kedua / $group2_unit)); // 30 - 60
						//jam ketiga = jam kedua - jam pertama , 30 menit - 
                        $jam_ketiga2 = $jam_ketiga;
                        if ($durasi < 1440)
                        {

                            //$biayaparkir_maks = ($tarif1 + $tarif2 + ($jam_ketiga2 * $group2_charge));
                            $biayaparkir_maks = ($tarif1 +$tarif2 + ($jam_ketiga2 * $group2_charge));
                            if ($maxcharge > 0 && ($biayaparkir_maks > $maxcharge))
                            {
                                $biayaparkir_maks = $maxcharge;
                            }
                            $durasi = 0;
							//$biayaparkir =  $biayaparkir + $biayaparkir_maks;
                        }
                        else
                        {
							
                            //$biayaparkir_maks = ($tarif1 + $tarif2 + ($jam_ketiga2 * $group2_charge));
                            $biayaparkir_maks = ($tarif2 + ($jam_ketiga2 * $group2_charge));
							//dd($biayaparkir_maks);
							
                            //$toleransi_maks = 1;
                            if ($maxcharge > 0 && ($biayaparkir_maks > $maxcharge))
                            {
                                    //total_maks = maxcharge;
                                $biayaparkir_maks = $maxcharge;
								$durasi = $durasi - 1440;
								 
                            }
							else{
								$durasi = 0;
							}
							
                        }
						
                    }
                    $biayaparkir = $biayaparkir + $biayaparkir_maks;
                }
             }
        }
		
		if($site == "LOP"){
			$jam  = ceil($jam / 60);
			if($jam <= 5){
				return array("biayaparkir"=>$biayaparkir,"lt_charge"=>$lt_charge,"jam"=>$durasi);
			}
			elseif($jam  >= 5 and $jam < 12 ){
				if($kendaraan == "MOBIL"){
					return array("biayaparkir"=>17500,"lt_charge"=>$lt_charge);
				}
				elseif($kendaraan == "BOX"){
					return array("biayaparkir"=>28000,"lt_charge"=>$lt_charge);
				}
				else{
					return array("biayaparkir"=>$biayaparkir,"lt_charge"=>$lt_charge,"jam"=>$jam);
				}
			}
			else{
				if($kendaraan == "MOBIL"){
					return array("biayaparkir"=>35000,"lt_charge"=>$lt_charge);
				}
				elseif($kendaraan == "BOX"){
					return array("biayaparkir"=>56000,"lt_charge"=>$lt_charge);
				}
				else{
					return array("biayaparkir"=>$biayaparkir,"lt_charge"=>$lt_charge,"jam"=>$jam);
				}
			}
			
		}else{
			return array("biayaparkir"=>$biayaparkir,"lt_charge"=>$lt_charge,"jam"=>$jam);
		}
		
		//return array("biayaparkir"=>$biayaparkir,"lt_charge"=>$lt_charge);
        
    }	
	
	public function saveTransaction(Request $request) {
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'ticket_no'   => 'required', 
				//'vehicle_code' => 'required',
				//'policeno' => 'required',
				'user_id' => 'required',
				'device_id' => 'required',
				'site_id' => 'required',
				'shift_id' => 'required',
				'lobby_id' => 'required',
				//'datetimein' => 'required',
				'datetimeout' => 'required',
				'duration' => 'required',
				'parking_fee' => 'required',
				'isLT' => 'required',
				'lt_charge' => 'required',
				'payment_type' => 'required',
				'cardno' => 'required'
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {
				//save
				if ($request->ticket_no == '123' || $request->ticket_no == 'Capture' || $request->ticket_no == '') {

					return response()->json([
						'success' => false,
						'message' => 'Invalid ticket number!',
						'data'   => $validator->errors()
					],200);

				}
				
				$img = DB::table("parking_in")
				->where("ti_qrcode",$request->ticket_no)
				->where("site_id",$request->site_id)
				->select("ti_img","lobby_id","ti_policeno","ti_datetime","ti_userin","ti_vehicle","car_type","car_color")
				->first();
				
				if($img == null){
					$img_list = "";
					$lobby_in = "";
					$ti_policeno = "NA";
				}
				else{
					$img_list = $img->ti_img;
					$lobby_in = $img->lobby_id;
					$ti_policeno = $img->ti_policeno;
				}
				DB::table('parking_out_mobile')->insert([
					'transid'   => mt_rand(1111111111,9999999999), 
					'qrcode'   => $request->ticket_no, 
					'policeno' => $ti_policeno, 
					'vehicle' => $img->ti_vehicle, 
					'userout' => $request->user_id, 
					'device_id' => $request->device_id, 
					'site_id' => $request->site_id, 
					'shift_id' => $request->shift_id, 
					'datetimein' => $img->ti_datetime,
					'datetimeout' => date_format(date_create($request->datetimeout),"Y-m-d H:i:s"), 
					'durasi' => $request->duration, 
					'parking_fee' => $request->parking_fee, 
					'lt_fee' => $request->lt_charge, 
					'img_in' => $img_list, 
					'islt' => $request->isLT, 
					'gatein' => $lobby_in, 
					'gateout' => $request->lobby_id, 
					'payment_type' => $request->payment_type, 
					'pr_cardno' => $request->cardno, 
					'pr_cardtype' => $request->card_type, 
					'pr_translog' => $request->trans_log, 
					'pr_balance' => $request->card_balance, 
					'userin' => $img->ti_userin, 
					'car_type' => $img->car_type, 
					'car_color' => $img->car_color, 
				]);
				
				if($request->isLT == 0){
					DB::table("parking_in")
					->where("ti_qrcode",$request->ticket_no)
					->where("site_id",$request->site_id)
					->delete();
				}
				
				
				return response()->json([
					'success' => true,
					'message' => 'Success',
					'data'   => ""
				],201);
				
			}
		}
	}
	
	public function pos_in(Request $request) {
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'site_id'   => 'required', 
				'device_id' => 'required',
				//'shift_id' => 'required',
				'lobby_id' => 'required',
				'police_no' => 'required',
				'vehicle' => 'required',
				'datetimein' => 'required'
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {
				//save
				
				$cek = DB::table("parking_in")
				->where("site_id" ,$request->site_id)
				->where("ti_policeno", $request->police_no)
				//->where("ti_datetime", $request->datetimein)
				->get()->count();
				//dd($cek);
				
				if($cek > 0){
					return response()->json([
					'success' => false,
					'message' => 'Kendaraan sudah di dalam area parkir!',
					'data'   => ""
					],200);
				}
				
				$qrcode = mt_rand(111111111111,999999999999)."PM".mt_rand(111,999);
				DB::table('parking_in')->insert([
					'ti_key'   => mt_rand(1111111111,9999999999), 
					'ti_qrcode'   => $qrcode, 
					'ti_policeno' => strtoupper($request->police_no), 
					'ti_vehicle' => $request->vehicle, 
					'ti_datetime' => $request->user_id, 
					'site_id' => $request->site_id, 
					'lobby_id' => $request->lobby_id, 
					//'shift_id' => $request->shift_id, 
					'ti_datetime' => $request->datetimein, 
					'ti_gatein' => $request->device_id, 
					'car_type' => $request->car_type, 
					'car_color' => $request->car_color, 
					'ti_cardno' => " ", 
					'ti_ticketno'   => $qrcode, 
					'ti_img'   => $request->parking_images, 
					'ti_userin' => "SYSTEM"
				]);
				//baru sampe sini utk save ke database parking_out_mobile
				return response()->json([
					'success' => true,
					'message' => 'Success',
					'qrcode'   => $qrcode
				],201);
				
			}
		}
	}
	private function konversi($menit)
    {
        $hasil = "";
        if ($menit < 59)
        {
            $hasil = ceil($menit) . " menit";
        }
        else if($menit > 1440)
        {
            $hari = $menit / 1440;
            $jam = ($menit % 1440) /60;
            $sisa = $jam % 60;
            $hasil = floor($hari) . " hr " . ceil($jam) . " jam " .ceil($sisa). " mnt";
           // $hasil = floor($menit / 60) . " jam  " .ceil($sisa). " menit";
        }
        else
        {
            $jam = $menit / 60;
            $sisa = $menit % 60;
            $hasil = floor($jam) . " jam " . ceil($sisa) . " menit";
        }
            return $hasil;
    }
	
	public function ovel(){
		/*
		$now = date('Y-m-d H:i:s');
		$data = DB::table("parking_in")
				->where("ti_qrcode","583447653575PM578")
				->where("site_id","SMB")
				->selectRaw("ti_key, ti_vehicle, DATE_FORMAT(ti_datetime,'%d-%m-%Y %H:%i') as parking_datetimein, 
                            '$now' as waktu_keluar, CEIL(TIMESTAMPDIFF(SECOND, ti_datetime, 
							NOW())/60) as durasi, DAYOFWEEK(ti_datetime) as hari, now()")
				->get();
		//dd($data);
		return response()->json([
					'success' => true,
					'message' => 'Success',
					'data'   => $data
				],201);
		*/
$sql = 
					"select users.userid,  users.shift_id,  users.fullname fullname, gateout, COUNT(*) AS qty, SUM(parking_fee) AS casual, 
            SUM(CASE WHEN lt_fee > 0 THEN 1 ELSE 0 END) AS qty_lt,
            SUM(CASE WHEN payment_type > 0 THEN 1 ELSE 0 END) AS prepaid_qty,
            SUM(CASE WHEN payment_type > 0 THEN parking_fee ELSE 0 END) AS prepaid_amount,
            SUM(CASE WHEN lt_fee > 0 THEN lt_fee ELSE 0 END) AS amount_lt,
            SUM(CASE WHEN userin = 'MANUAL' THEN 1 ELSE 0 END) AS qty_manual,
            SUM(CASE WHEN userin = 'MANUAL' THEN parking_fee ELSE 0 END) AS amount_manual, 
			DATE_FORMAT(users.startshift,'%Y-%m-%d %H:%i:%s') startshift, 
			DATE_FORMAT(users.endshift,'%Y-%m-%d %H:%i:%s') endshift
            FROM parking_out_mobile right join users on parking_out_mobile.userout = users.userid 
            where parking_out_mobile.shift_id = '123123'
            AND users.ustatus = 'E'  and users.userid='PP1' group by users.userid,
			users.fullname, parking_out_mobile.gateout, users.startshift, users.endshift, users.shift_id";
			
				$data = DB::select(DB::RAW($sql));
				
				//dd($data);
				foreach($data as $rs){
					$gate = $rs->gateout;
					$username = $rs->fullname;
					$userid = $rs->userid;
					$start_shift = $rs->startshift;
					$end_shift = $rs->endshift;
					$casual_amount = $rs->casual;
					$casual_qty =$rs->qty;
					$lt_amount = $rs->amount_lt;
					$lt_qty = $rs->qty_lt;  //$rs->qty_lt;
					$manual_amount = $rs->amount_manual;  //$rs->amount_manual;
					$manual_qty = $rs->qty_manual;  //$rs->qty_manual;
					$prepaid_qty = $rs->prepaid_qty;  //$rs->prepaid_qty;
					$prepaid_amount = $rs->prepaid_amount;
					$shift_id = $rs->shift_id;
//insert into settlement (userid, gate, start_shift, end_shift, casual_amount, casual_qty,"
//        + "lt_amount, lt_qty, manual_amount, manual_qty, shift_id, prepaid_qty,prepaid_amount) values ("
//        + "'" + userid + "','" + gate + "','" + start_shift + "','" + end_shift + "','" + casual_amount + "','" + casual_qty + "',"
//       + "'" + lt_amount + "','" + lt_qty + "','" + manual_amount + "','" + manual_qty + "','" + shift_id + "','" + prepaid_qty + "','" + prepaid_amount + "')
					 DB::table("settlement")
					 ->insert([
						"userid"=>$userid,
						"gate"=>$gate,
						"start_shift"=>$start_shift,
						"end_shift"=>$end_shift,
						"casual_amount"=>$casual_amount,
						"casual_qty"=>$casual_qty,
						"lt_amount"=>$lt_amount,
						"lt_qty"=>$lt_qty,
						"manual_amount"=>$manual_amount,
						"manual_qty"=>$manual_qty,
						"shift_id"=>$shift_id,
						"prepaid_qty"=>$prepaid_qty,
						"prepaid_amount"=>$prepaid_amount
					 ]);
				}
				return 'ok';
				
				//dd($rs);
				
	}
	
	function upload_img(Request $request){
		//dd($request->all());
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'img_upload' => 'required'
			]);
			
			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid post data!',
					'data'   => $validator->errors()
				],200);

			} else {
				
				$fname = mt_rand(111111,999999);
				
				//$base64DataString  = "data:image/jpeg;base64, ";
				$base64DataString  = $request->img_upload;
 
				$pattern = '/data:image\/(.+);base64,(.*)/';
				preg_match($pattern, $base64DataString, $matches);

				// image file extension
				$imageExtension = $matches[1];

				// base64-encoded image data
				$encodedImageData = $matches[2];

				// decode base64-encoded image data
				$decodedImageData = base64_decode($encodedImageData);

				// save image data as file
				file_put_contents(storage_path()."/parking_image/"."$fname.{$imageExtension}", $decodedImageData);
				
				DB::table('parking_image')->insert([
					'img_id'   => $fname,
					'img_name'   => $fname.".".$imageExtension,
				]);
				
				
				return response()->json([
					'success' => true,
					'message' => 'Success',
					'img_id'   => $fname
				],200);
				
			}
		}
	}
	
	function ticketnote(Request $request){
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{
			$validator = Validator::make($request->all(), [
				'site_id'   => 'required',
			]);

			if ($validator->fails()) {

				return response()->json([
					'success' => false,
					'message' => 'Invalid request parameter!',
					'data'   => $validator->errors()
				],200);

			} else {
				
				$data = DB::table("setting_ticket")
				->where("siteid",$request->site_id)
				->get()->first();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'',
						'data'    => null
						], 200);
				}
				else{
					return response()->json([
						'success' => true,
						'message' =>'OK',
						'data'    => $data
						], 200);
				}
			}
		}
	}
	
	function vehicletype(){
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{

				$data = DB::table("vehicle_brand")
				->leftJoin("vehicle_type","vehicle_brand.id","=","vehicle_type.brand_id")
				->selectRAW("CONCAT(vehicle_brand.brand_name,' > ', vehicle_type.type) AS vehicletype")
				->get();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'',
						'data'    => null
						], 200);
				}
				else{
					return response()->json([
						'success' => true,
						'message' =>'',
						'data'    => $data
						], 200);
				}
			
		}
	}
	
	function vehiclecolor(){
		if($this->getBearerToken()  ==  false){
			return response()->json([
				'success' => false,
				'message' =>'Invalid credential',
				'data'    => null
				], 200);
		}
		else
		{

				$data = DB::table("vehicle_color")
				->get();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'',
						'data'    => null
						], 200);
				}
				else{
					return response()->json([
						'success' => true,
						'message' =>'',
						'data'    => $data
						], 200);
				}
			
		}
	}
}