<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Validator;
use Auth;
use App\Responses;
use App\Helper;
use App\Models\Vehicles;
use App\Models\Devices;
use App\Models\VehiclesDetail;
use App\Models\Users;
use App\Models\UserLogs;

class VehiclesController extends Controller
{
	public function api_list_vehicles(Request $req)
	{
		try {
			$now = time();
			$input = [];
			$rulesInput = [];

			// validasi input
			// $isValidInput = Validator::make($input, $rulesInput);
			// if (!$isValidInput->passes()) {
			// 	$apiResp = Responses::bad_input($isValidInput->messages()->first());
			// 	return new Response($apiResp, $apiResp['meta']['code']);
			// }

			$filter = [];
			if ($req->cptid) {
				$filter["company"] = $req->cptid;
			}
			$list = Vehicles::listVehicles($req->auth, $filter);

			foreach ($list as $key => $row) {
				$list[$key]->DT_RowIndex = $key + 1;
				// $list[$key]->mileage_km = '-';
				// $list[$key]->div_name = 'All Division';
				// $list[$key]->group_name = 'All Group';
				// $list[$key]->track_schedule = $row->track_sch_h.'/'.$row->track_sch_d; // combine track_sch_h + track_sch_d
				// $list[$key]->is_track_holiday_text = ($list[$key]->is_track_holiday == Vehicles::ENABLED_TRACK_HOLIDAY) ? 'Enabled' : 'Disabled';
				// $list[$key]->alert_zones = '-';
				// $list[$key]->cameras = '-';
				$list[$key]->action = "-";
			}

			$apiResp = Responses::success("success list vehicles");
			$apiResp["data"] = $list;
			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}

	public function api_list_vehicles1(Request $req)
	{
		try {
			$now = time();
			$input = [];
			$rulesInput = [];

			$filter = [];
			if ($req->cptid) {
				$filter["company"] = $req->cptid;
			}
			$list = DB::select("SELECT
					v.id, v.name, v.device_id, nopol1, nopol2, nopol3, v.sum_milleage, 
					fvhc_img, vyear, t.`desc` type_name, c_name company_name, rltm.crt_d, rltm.crt crt_rltm,
					dvc.crt, dvc.simcard, fuel_curr, dvc.protocol, v.cat_id, vc.name cat_name
				FROM t_vehicles as v
				INNER JOIN t_vehicles_detail AS vd ON v.id = vd.vid
				LEFT JOIN t_vehicles_types AS t ON v.type_id = t.id
				LEFT JOIN t_users AS vdr ON v.vendor_id = vdr.id
				LEFT JOIN t_clients AS client ON vdr.client_group_id = client.id
				LEFT JOIN t_devices AS dvc ON v.device_id = dvc.device_id
				left join t_gps_tracks_rltm rltm on rltm.vhc_id = v.id
				LEFT JOIN t_vehicles_cats AS vc ON v.cat_id = vc.id
				WHERE v.dlt is null
				ORDER BY v.id ASC			
			");

			foreach ($list as $key => $row) {
				$list[$key]->DT_RowIndex = $key + 1;
				$list[$key]->action = "-";
			}

			$apiResp = Responses::success("success list vehicles");
			$apiResp["data"] = $list;
			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}

	public function api_show_vehicle(Request $req, $vid)
	{
		try {
			$now = time();

			$input = [
				"vid" => $vid,
			];
			$rulesInput = [
				"vid" => "required|integer|not_in:0",
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$vehicle = Vehicles::showVehicleById($vid);
			if (count($vehicle) < 1) {
				$apiResp = Responses::not_found("vehicle not found");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$apiResp = Responses::success("success get detail vehicle");
			$apiResp["data"] = $vehicle[0];
			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}

	public function api_add_vehicle(Request $req)
	{
		$url_fvhc = "";
		$url_stnk = "";
		if ($req->hasFile("fvhc_file")) {
			$fileFvhc = $req->file("fvhc_file");
			$fvhcContent = file_get_contents($fileFvhc->getRealPath());
			$req->fvhc_base64 = base64_encode($fvhcContent);
		} else {
			$req->fvhc_base64 = null;
		}

		// Ambil file stnk_file dan ubah ke base64
		if ($req->hasFile("stnk_file")) {
			$fileStnk = $req->file("stnk_file");
			$stnkContent = file_get_contents($fileStnk->getRealPath());
			$req->stnk_base64 = base64_encode($stnkContent);
		} else {
			$req->stnk_base64 = null;
		}

		$req->dvc_id = $req->dvc_id === "undefined" ? null : $req->dvc_id;

		try {
			$now = time();

			$device_id = str_pad($req->device_id, Vehicles::MAX_DEVICE_ID, "0", STR_PAD_LEFT);

			$input = [
				"front_vehicle_photo" => $req->fvhc_base64,
				"dvc_id" => $req->dvc_id,
				"simcard" => $req->simcard,
				"device_id" => $req->device_id,
				"vehicle_name" => $req->vhc_name,
				"brand_id" => $req->brand_id,
				"type_id" => $req->type_id,
				"cat_id" => $req->cat_id,
				"model_id" => $req->model_id,
				"speed_limit" => $req->speed_limit,
				"fuel_capacity" => $req->fuel_capacity,
				"fuel_drop_treshold" => $req->fuel_drop_treshold,
				"max_pressure" => $req->max_pressure,
				"current_driver" => $req->d_current,
				"assign_driver" => $req->d_assign,
				"stnk_photo" => $req->stnk_base64,
				"stnk_exp" => $req->stnk_exp,
				"nopol1" => $req->nopol1,
				// "nopol2" => $req->nopol2,
				// "nopol3" => $req->nopol3,
				"manufacture_year" => $req->stnk_vyear,
				"cylinder_capacity" => $req->cc,
				"vehicle_identity_number" => $req->vin,
				"engine_number" => $req->en,
				"vehicle_color" => $req->color,
				"fuel_type" => $req->fuel_type,
				"license_plat_color" => $req->tnkb_color,
				"regis_year" => $req->regis_year,
				"tax_exp" => $req->tax_exp,
				// "kir_exp" => $req->kir_exp,
				// "vendor_id" => $req->vendor_id,
				"dc_code" => $req->dc_code,
				"pool_code" => $req->pool_code,
			];
			$rulesInput = [
				"front_vehicle_photo" => "required|string",
				"dvc_id" => "nullable|integer",
				"simcard" => "nullable|numeric",
				"device_id" => "nullable|numeric",
				"vehicle_name" => "required|string",
				"brand_id" => "required|integer",
				"type_id" => "required|integer",
				"cat_id" => "required|integer",
				"model_id" => "nullable|integer",
				"speed_limit" => "required|numeric",
				// "fuel_capacity" => "required|numeric",
				// "fuel_drop_treshold" => "required|numeric",
				// "max_pressure" => "required|numeric",
				"current_driver" => "nullable|integer",
				"assign_driver" => "nullable|integer",
				"stnk_photo" => "required|string",
				"stnk_exp" => "required|date_format:Y-m-d",
				"nopol1" => "required|string",
				// "nopol2" => "required|string|max:4",
				// "nopol3" => "required|string|max:3",
				"manufacture_year" => "required|digits:4",
				"cylinder_capacity" => "required|integer",
				"vehicle_identity_number" => "required|string",
				"engine_number" => "required|string",
				"vehicle_color" => "required|string|min:3|max:25",
				"fuel_type" => "required|string|min:3|max:25",
				"license_plat_color" => "required|string|min:3|max:25",
				"regis_year" => "required|digits:4",
				"tax_exp" => "required|date_format:Y-m-d",
				// "kir_exp" => "required|date_format:Y-m-d",
				// "vendor_id" => "nullable|integer|not_in:0",
				"dc_code" => "nullable|string",
				"pool_code" => "nullable|string",
			];

			if ($req->auth->role == Users::ROLE_VENDOR) {
				$rulesInput["simcard"] = "nullable";
			}

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			if (strlen($req->device_id) > Vehicles::MAX_DEVICE_ID) {
				$apiResp = Responses::bad_input("device_id max length is " . Vehicles::MAX_DEVICE_ID);
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			// if ($device_id !== str_pad(0, Vehicles::MAX_DEVICE_ID, "0", STR_PAD_LEFT)) {
			//     $uniqDeviceId = Vehicles::getVehicleByDeviceId($device_id);
			//     if (count($uniqDeviceId) > 0) {
			//         $apiResp = Responses::bad_request("device id has been used");
			//         return new Response($apiResp, $apiResp["meta"]["code"]);
			//     }
			// }

			// $uniqSimcard = Vehicles::getVehicleBySimcard($req->simcard);
			// if (count($uniqSimcard) > 0) {
			//     $apiResp = Responses::bad_request("simcard has been used");
			//     return new Response($apiResp, $apiResp["meta"]["code"]);
			// }

			$uniqPlatNo = Vehicles::getVehicleByPlatNo($req->nopol1, $req->nopol2, $req->nopol3);
			if (count($uniqPlatNo) > 0) {
				$apiResp = Responses::bad_request("Vehicle identity number has been used");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			DB::beginTransaction();

			$insVhc = [
				"name" => $req->vhc_name,
				"dvc_id" => $req->dvc_id ?? 0,
				"device_id" => $device_id,
				"simcard" => $req->simcard ?? 0,
				"brand_id" => $req->brand_id,
				"type_id" => $req->type_id,
				"cat_id" => $req->cat_id,
				"nopol1" => strtoupper($req->nopol1),
				// "nopol2" => strtoupper($req->nopol2),
				// "nopol3" => strtoupper($req->nopol3),
				"sum_milleage" => $req->mileage ?? 0,
				"c_did" => $req->d_current ?? 0,
				"a_did" => $req->d_assign ?? 0,
				"is_track_holiday" => Vehicles::DEFAULT_TRACK_HOLIDAY,
				"track_sch_d" => Vehicles::DEFAULT_TRACK_SCH_D,
				"track_sch_h" => Vehicles::DEFAULT_TRACK_SCH_H,
				// "client_group_id" => $req->auth->client_group_id ?? 1,
				// "vendor_id" => $req->auth->client_group_id ?? 1,
				"client_group_id" => 1,
				"vendor_id" => 1,
				"crt" => $now,
				"crt_by" => $req->auth->uid,
				"updt" => $now,
				"updt_by" => $req->auth->uid,

			];
			// dd($insVhc);
			if ($req->model_id) {
				$insVhc["model_id"] = $req->model_id;
			}
			if ($req->auth->role == Users::ROLE_VENDOR) {
				// $insVhc["vendor_id"] = $req->auth->uid;
				$insVhc["vendor_id"] = 1;
				$insVhc["simcard"] = 0;
			} else {
				// $insVhc["vendor_id"] = $req->vendor_id ?? 1;
				$insVhc["vendor_id"] = 1;
			}
			$vid = Vehicles::addVehicle($insVhc);

			if ($req->auth->role == Users::ROLE_VENDOR) {
				$getUsrId = DB::table("t_users")
					->where("id", Auth::user()->id)
					->first();
				$vhclid = DB::table("t_vehicles")->insertGetId($insVhc);
				$new = $getUsrId->vhcs . "," . $vhclid;
				$dtupdate = [
					"vhcs" => $new,
				];
				DB::table("t_users")
					->where("id", Auth::user()->id)
					->update($dtupdate);
				$dtUpdataIsTracking = [
					"is_tracking" => 1,
				];
				DB::table("t_users")
					->where("id", Auth::user()->id)
					->update($dtUpdataIsTracking);
			}
			$url_fvhc = "vehicles/$vid/front_$now.jpeg";
			if (!Storage::disk("public")->put($url_fvhc, base64_decode($req->fvhc_base64))) {
				DB::rollBack();
				$apiResp = Responses::bad_request("fail upload front photo");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}
			$url_stnk = "vehicles/$vid/stnk_$now.jpeg";
			if (!Storage::disk("public")->put($url_stnk, base64_decode($req->stnk_base64))) {
				Storage::disk("public")->delete($url_fvhc);
				DB::rollBack();
				$apiResp = Responses::bad_request("fail upload front photo");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$insDetail = [
				"vid" => $vid,
				"speed_limit" => $req->speed_limit,
				"fuel_capacity" => $req->fuel_capacity,
				"fuel_drop_treshold" => $req->fuel_drop_treshold,
				"max_pressure" => $req->max_pressure,
				"fvhc_img" => $url_fvhc,
				"stnk_img" => $url_stnk,
				"stnk_exp" => $req->stnk_exp,
				"vyear" => $req->stnk_vyear, // manufacture_year
				"cc" => $req->cc, // cylinder_capacity
				"vin" => strtoupper($req->vin), // vehicle_identity_number
				"en" => strtoupper($req->en), // engine_number
				"vcolor" => strtoupper($req->color),
				"fuel_type" => strtoupper($req->fuel_type),
				"tnkb_color" => strtoupper($req->tnkb_color), // license_plat_color
				"regis_year" => $req->regis_year,
				"tax_exp" => $req->tax_exp,
				"kir_exp" => $req->kir_exp,
				"dc_code" => $req->dc_code,
				"pool_code" => $req->pool_code,

			];
			VehiclesDetail::addDetail($insDetail);

			$apiResp = Responses::created("success add new vehicle");

			DB::commit();

			$log = [
				"module" => "Vehicle",
				"action" => "Create",
				"desc" => "Add new vehicle: " . $req->vhc_name,
			];
			UserLogs::insert(Auth::user()->id, $log);

			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			Storage::disk("public")->delete($url_fvhc);
			Storage::disk("public")->delete($url_stnk);
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}

	public function api_edit_vehicle(Request $req, $vid)
	{
		$url_fvhc = "";
		$url_stnk = "";

		try {
			$now = time();

			$device_id = str_pad($req->device_id, Vehicles::MAX_DEVICE_ID, "0", STR_PAD_LEFT);

			$input = [
				"vid" => 1,
				"front_vehicle_photo" => $req->fvhc_base64,
				"dvc_id" => $req->dvc_id ?? 0,
				"simcard" => $req->simcard,
				"device_id" => $req->device_id,
				"vehicle_name" => $req->vhc_name,
				"brand_id" => $req->brand_id,
				"type_id" => $req->type_id,
				"cat_id" => $req->cat_id,
				"model_id" => $req->model_id,
				"speed_limit" => $req->speed_limit,
				"sum_milleage" => $req->mileage,
				"fuel_capacity" => $req->fuel_capacity,
				"fuel_drop_treshold" => $req->fuel_drop_treshold,
				"max_pressure" => $req->max_pressure,
				"current_driver" => $req->d_current,
				"assign_driver" => $req->d_assign,
				"stnk_photo" => $req->stnk_base64,
				"stnk_exp" => $req->stnk_exp,
				"nopol1" => $req->nopol1,
				// "nopol2" => $req->nopol2,
				// "nopol3" => $req->nopol3,
				"manufacture_year" => $req->stnk_vyear,
				"cylinder_capacity" => $req->cc,
				"vehicle_identity_number" => $req->vin,
				"engine_number" => $req->en,
				"vehicle_color" => $req->color,
				"fuel_type" => $req->fuel_type,
				"license_plat_color" => $req->tnkb_color,
				"regis_year" => $req->regis_year,
				"tax_exp" => $req->tax_exp,
				// "kir_exp" => $req->kir_exp,
				// "vendor_id" => $req->vendor_id,
				"dc_code" => $req->dc_code,
				"pool_code" => $req->pool_code,
			];
			$rulesInput = [
				"vid" => "required|integer|not_in:0",
				"front_vehicle_photo" => "nullable|string",
				// "dvc_id" => "nullable|integer",
				"simcard" => "nullable|numeric",
				"device_id" => "nullable|numeric",
				"vehicle_name" => "required|string",
				"brand_id" => "required|integer",
				"type_id" => "required|integer",
				"cat_id" => "required|integer",
				"model_id" => "nullable|integer",
				"speed_limit" => "required|numeric",
				"sum_milleage" => "required|numeric",
				// "fuel_capacity" => "required|numeric",
				// "fuel_drop_treshold" => "required|numeric",
				// "max_pressure" => "required|numeric",
				"current_driver" => "nullable|integer",
				"assign_driver" => "nullable|integer",
				"stnk_photo" => "nullable|string",
				"stnk_exp" => "required|date_format:Y-m-d",
				"nopol1" => "required|string",
				// "nopol2" => "required|string|max:4",
				// "nopol3" => "required|string|max:3",
				"manufacture_year" => "required|digits:4",
				"cylinder_capacity" => "required|integer",
				"vehicle_identity_number" => "required|string",
				"engine_number" => "required|string",
				"vehicle_color" => "required|string|min:3|max:25",
				"fuel_type" => "required|string|min:3|max:25",
				"license_plat_color" => "required|string|min:3|max:25",
				"regis_year" => "required|digits:4",
				"tax_exp" => "required|date_format:Y-m-d",
				// "kir_exp" => "required|date_format:Y-m-d",
				// "vendor_id" => "nullable|integer|not_in:0",
				"dc_code" => "nullable|string",
				"pool_code" => "nullable|string",
			];

			if ($req->auth->role == Users::ROLE_VENDOR) {
				$rulesInput["simcard"] = "nullable";
			}

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			if (strlen($req->device_id) > Vehicles::MAX_DEVICE_ID) {
				$apiResp = Responses::bad_input("device id max length is " . Vehicles::MAX_DEVICE_ID);
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$vhc = Vehicles::getVehicleById($vid);
			if (count($vhc) < 1) {
				$apiResp = Responses::bad_request("vehicle not found");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}
			$vd = VehiclesDetail::getDetailByVid($vid);
			if (count($vd) < 1) {
				$apiResp = Responses::bad_request("vehicle not found");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			// if ($req->dvc_id) {
			//     $uniqDeviceId = Vehicles::getVehicleByDeviceId($device_id);
			//     if (count($uniqDeviceId) > 0) {
			//         $notSameUser = 1;
			//         foreach ($uniqDeviceId as $key => $row) {
			//             if ($row->id == $vid) {
			//                 $notSameUser = 0;
			//             }
			//         }
			//         if ($notSameUser) {
			//             $apiResp = Responses::bad_request("device id has been used");
			//             return new Response($apiResp, $apiResp["meta"]["code"]);
			//         }
			//     }
			// }

			$uniqSimcard = Vehicles::getVehicleBySimcard($req->simcard);
			if (count($uniqSimcard) > 0) {
				$notSameUser = 1;
				foreach ($uniqSimcard as $key => $row) {
					if ($row->id == $vid) {
						$notSameUser = 0;
					}
				}
				if ($notSameUser) {
					$apiResp = Responses::bad_request("simcard has been used");
					return new Response($apiResp, $apiResp["meta"]["code"]);
				}
			}

			$uniqPlatNo = Vehicles::getVehicleByPlatNo($req->nopol1, $req->nopol2, $req->nopol3);
			if (count($uniqPlatNo) > 0) {
				$notSameUser = 1;
				foreach ($uniqPlatNo as $key => $row) {
					if ($row->id == $vid) {
						$notSameUser = 0;
					}
				}
				if ($notSameUser) {
					$apiResp = Responses::bad_request("plat number has been used");
					return new Response($apiResp, $apiResp["meta"]["code"]);
				}
			}

			DB::beginTransaction();

			$updtVhc = [
				"name" => $req->vhc_name,
				"dvc_id" => $req->dvc_id,
				"device_id" => $device_id,
				"simcard" => (int) $req->simcard,
				"brand_id" => $req->brand_id,
				"type_id" => $req->type_id,
				"cat_id" => $req->cat_id,
				"nopol1" => strtoupper($req->nopol1),
				"nopol2" => strtoupper($req->nopol2),
				"nopol3" => strtoupper($req->nopol3),
				"c_did" => $req->d_current ?? 0,
				"a_did" => $req->d_assign ?? 0,
				"sum_milleage" => $req->mileage ?? 0,
				"is_track_holiday" => Vehicles::DEFAULT_TRACK_HOLIDAY,
				"track_sch_d" => Vehicles::DEFAULT_TRACK_SCH_D,
				"track_sch_h" => Vehicles::DEFAULT_TRACK_SCH_H,
				"vendor_id" => 1,
				"updt" => $now,
				"updt_by" => $req->auth->uid,
			];
			if ($req->model_id) {
				$updtVhc["model_id"] = $req->model_id;
			}
			if ($req->auth->role == Users::ROLE_VENDOR) {
				$updtVhc["vendor_id"] = $req->auth->uid;
				// $updtVhc["simcard"] = (int) $uniqDeviceId[0]->simcard;
			} else {
				$updtVhc["vendor_id"] = $req->vendor_id ?? 1;
			}
			Vehicles::updateVehicle($vid, $updtVhc);

			if ($req->dvc_id) {
				Devices::updateDevice($req->dvc_id, [
					"is_assigned" => Devices::IS_ASSIGNED,
				]);
			} else {
				Devices::updateDevice($vhc[0]->dvc_id, [
					"is_assigned" => Devices::IS_UNASSIGNED,
				]);
			}

			if ($req->fvhc_base64) {
				$url_fvhc = "vehicles/$vid/front_$now.jpeg";
				if (!Storage::disk("public")->put($url_fvhc, base64_decode($req->fvhc_base64))) {
					DB::rollBack();
					$apiResp = Responses::bad_request("fail upload front photo");
					return new Response($apiResp, $apiResp["meta"]["code"]);
				}
				Storage::disk("public")->delete($vd[0]->fvhc_img);
			}
			if ($req->stnk_base64) {
				$url_stnk = "vehicles/$vid/stnk_$now.jpeg";
				if (!Storage::disk("public")->put($url_stnk, base64_decode($req->stnk_base64))) {
					Storage::disk("public")->delete($url_fvhc);
					DB::rollBack();
					$apiResp = Responses::bad_request("fail upload front photo");
					return new Response($apiResp, $apiResp["meta"]["code"]);
				}
				Storage::disk("public")->delete($vd[0]->stnk_img);
			}

			$updtDetail = [
				"vid" => $vid,
				"speed_limit" => $req->speed_limit,
				"fuel_capacity" => $req->fuel_capacity,
				"fuel_drop_treshold" => $req->fuel_drop_treshold,
				"max_pressure" => $req->max_pressure,
				"stnk_exp" => $req->stnk_exp,
				"vyear" => $req->stnk_vyear, // manufacture_year
				"cc" => $req->cc, // cylinder_capacity
				"vin" => strtoupper($req->vin), // vehicle_identity_number
				"en" => strtoupper($req->en), // engine_number
				"vcolor" => strtoupper($req->color),
				"fuel_type" => strtoupper($req->fuel_type),
				"tnkb_color" => strtoupper($req->tnkb_color), // license_plat_color
				"regis_year" => $req->regis_year,
				"tax_exp" => $req->tax_exp,
				"kir_exp" => $req->kir_exp,
				"dc_code" => $req->dc_code,
				"pool_code" => $req->pool_code,
			];
			if ($req->fvhc_base64) {
				$updtDetail["fvhc_img"] = $url_fvhc;
			}
			if ($req->stnk_base64) {
				$updtDetail["stnk_img"] = $url_stnk;
			}
			VehiclesDetail::updateDetailByVid($vid, $updtDetail);

			DB::commit();

			$apiResp = Responses::success("success update vehicle");

			$log = [
				"module" => "Vehicle",
				"action" => "Update",
				"desc" => "Update vehicle: " . $req->vhc_name,
			];
			UserLogs::insert(Auth::user()->id, $log);
			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			Storage::disk("public")->delete($url_fvhc);
			Storage::disk("public")->delete($url_stnk);
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}

	public function api_del_vehicle(Request $req, $vid)
	{
		try {
			$now = time();

			$input = [
				"vid" => $vid,
			];
			$rulesInput = [
				"vid" => "required|integer|not_in:0",
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$vehicle = Vehicles::showVehicleById($vid);
			if (count($vehicle) < 1) {
				$apiResp = Responses::not_found("vehicle not found");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			DB::beginTransaction();

			$device_id = str_pad(0, Devices::MAX_DEVICE_ID, "0", STR_PAD_LEFT);
			Vehicles::updateVehicle($vid, [
				"dvc_id" => 0,
				"device_id" => $device_id,
				"simcard" => 0,
				"dlt" => $now,
				"dlt_by" => $req->auth->uid,
			]);
			if ($vehicle[0]->dvc_id != 0) {
				Devices::updateDevice($vehicle[0]->dvc_id, [
					"is_assigned" => Devices::IS_UNASSIGNED,
				]);
			}

			// Storage::disk('public')->delete($vehicle[0]->fvhc_img);
			// Storage::disk('public')->delete($vehicle[0]->stnk_img);

			DB::commit();

			$apiResp = Responses::success("success delete vehicle");

			$log = [
				"module" => "Vehicle",
				"action" => "Delete",
				"desc" => "Delete vehicle: " . $vehicle[0]->name,
			];
			UserLogs::insert(Auth::user()->id, $log);
			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}

	public function api_search_device_id(Request $req)
	{
		try {
			$now = time();

			$input = [
				"device_id" => $req->device_id,
			];
			$rulesInput = [
				"device_id" => "required|numeric",
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			if (strlen($req->device_id) > Vehicles::MAX_DEVICE_ID) {
				$apiResp = Responses::bad_input("device id max length is " . Vehicles::MAX_DEVICE_ID);
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$device_id = str_pad($req->device_id, Vehicles::MAX_DEVICE_ID, "0", STR_PAD_LEFT);
			$devices = Vehicles::getVehicleByDeviceId($device_id);

			if (count($devices) < 1) {
				$apiResp = Responses::not_found("device id not found");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$apiResp = Responses::success("success search device id");
			$apiResp["data"] = $devices;

			DB::commit();
			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}

	public function api_search_nopol(Request $req)
	{
		try {
			$now = time();

			$input = [
				"nopol" => $req->nopol,
			];
			$rulesInput = [
				"nopol" => "required|string",
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$nopol = explode(" ", strtoupper($req->nopol));
			$cNopol = count($nopol);
			if ($cNopol === 3) {
			} elseif ($cNopol === 2) {
				$nopol[2] = "";
			} elseif ($cNopol === 1) {
				$nopol[1] = "";
				$nopol[2] = "";
			} else {
				$apiResp = Responses::bad_input("Nomor polisi kendaraan tidak valid");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$vehicles = Vehicles::searchVehicleByPlatNo($nopol[0], $nopol[1], $nopol[2]);

			if (count($vehicles) < 1) {
				$apiResp = Responses::not_found("vehicles not found");
				return new Response($apiResp, $apiResp["meta"]["code"]);
			}

			$apiResp = Responses::success("success search vehicles");
			$apiResp["data"] = $vehicles;

			DB::commit();
			return new Response($apiResp, $apiResp["meta"]["code"]);
		} catch (\Exception $e) {
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return new Response($apiResp, $apiResp["meta"]["code"]);
		}
	}
}
