<?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));
    }
	
	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',
				'passwd' => 'required',
			]);

			if ($validator->fails()) {

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

			} else {

				$data = DB::table("users")
				->where("site_id",$request->site_id)
				->where("userid",$request->user_id)
				->where("pwd",md5($request->passwd))
				->select("fullname")
				->get()->first();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Invalid login',
						'data'    => null
						], 200);
				}
				else{
					return response()->json([
						'success' => true,
						'message' =>'Login 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 {

				
					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("mastervehicle")
				->where("site_id",$request->site_id)
				->get();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Data not found',
						'parking_fee'    => 0,
						'durasi1'    => "",
						'durasi2'    => "",
						'datetimeout'    => null,
						], 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->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")
				->where("ti_qrcode",$request->ticket_no)
				->where("site_id",$request->site_id)
				->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")
				->get()->first();
				
				if($data == null){
					return response()->json([
						'success' => false,
						'message' =>'Data not found',
						'parking_fee'    => 0,
						'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,
						'parking_fee'    => $this->hitung($request->vehicle_code,$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)
    {
		if($site == "LOP"){
			//$nama_hari = date('l', strtotime(date('Y-m-d')));
			$nama_hari = date('l', strtotime(date('Y-m-d')));
			$now = date('Y-m-d', strtotime('now +1 hour'));
		}
		else{
			$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($nama_hari == "Saturday" || $ceklibur > 0)
        {
            $hasil = "Y";
        }
        else
        {
             $hasil = "N";
        }
        return $hasil;
    }
		
	private function hitung($kendaraan, $durasi, $isLT, $site)
    {
       
        if ($this->cekHari($site) == "Y")
        {
            $rstarif = DB::table("casualcharges")     
			->where("hari","H")
			->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("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)
				->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;
				}
                  
		}
        
            //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;//1000
                    $jam_kedua = ($durasi - $group1_unit); //90 - 60
                    if ($jam_kedua < 1)
                    {
                        $biayaparkir_maks = $tarif1; //1000
                        $durasi = 0;
                    }
                    else
                    {
                        $tarif2 = $group2_charge; //1000
                        $jam_ketiga = (ceil($jam_kedua / $group2_unit)); // 90 / 60
                        $jam_ketiga2 = $jam_ketiga;
                        if ($durasi < 1440)
                        {

                            $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));
							//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;
                }
             }
        }
        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',
				'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
				
				DB::table('parking_out_mobile')->insert([
					'transid'   => mt_rand(1111111111,9999999999), 
					'qrcode'   => $request->ticket_no, 
					'policeno' => $request->policeno, 
					'vehicle' => $request->vehicle_code, 
					'userout' => $request->user_id, 
					'device_id' => $request->device_id, 
					'site_id' => $request->site_id, 
					'datetimein' => $request->datetimein,
					'datetimeout' => $request->datetimeout, 
					'durasi' => $request->duration, 
					'parking_fee' => $request->parking_fee, 
					'lt_fee' => $request->lt_charge, 
					'islt' => $request->isLT, 
					'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' => "", 
				]);
				//baru sampe sini utk save ke database parking_out_mobile
				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',
				'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' => $request->police_no, 
					'ti_vehicle' => $request->vehicle, 
					'ti_datetime' => $request->user_id, 
					'site_id' => $request->site_id, 
					'ti_datetime' => $request->datetimein, 
					'ti_gatein' => $request->device_id, 
					'ti_cardno' => " ", 
					'ti_ticketno'   => $qrcode, 
					'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);
	}
}