@extends('app.app')

@section('title')
	Master Devices
@endsection

@section('customcss')
	<style>
		/* .select2-container {
																																									z-index: 99999;
																																								} */
	</style>
@endsection

@section('content')
	<div class="container-fluid">
		<div class="content">
			<div class="card">
				<div class="card-header">
					<div class="row d-flex align-items-center">
						<div class="col-3">
							<p class="card-title text-bold mb-0">Device (<span id="count_devices">0</span>)</p>
						</div>
						@can('config_master_device.create')
							<div class="col text-end">
								<button id="btnMdlNewDevice" class="btn btn-sm btn-danger">Add New Device</button>
							</div>
						@endcan

						<div class="col-auto text-end ps-0">
							{{-- <button class="btn btn-sm btn-danger">Upload</button> --}}
							{{-- <button class="btn btn-sm btn-danger">Download</button> --}}
						</div>
					</div>
				</div>
				<div class="card-body">
					<div class="table-responsive">
						<table id="tDevices" class="table table-hover dataTable">
							<thead>
								<tr class="">
									<th class="">#</th>
									<th class="text-center">Action</th>
									<th class="">Device ID</th>
									<th class="">Device Type</th>
									<th class="">Name</th>
									<th class="text-end">SIM Card</th>
									<th class="text-end">Type</th>
									<th class="text-center">Status</th>
									<th class="text-center">Installation</th>
									<th class="text-center">Vehicle</th>
									<th class="text-center">Availability</th>
								</tr>
							</thead>
							<tbody>

							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlNewDevice"
		aria-labelledby="mdlNewDeviceLabel" aria-hidden="true">
		<div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="mdlNewDeviceLabel">Tambah Device Baru</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body">
					<form>
						{{-- Primary --}}
						<div class="mb-3">
							<div class="border-bottom">
								<h6>Data Device</h6>
							</div>
							<div class="row">
								<div class="col-sm-6">
									<label for="add-device_id" class="col-form-label">Device ID<span
											class="text-danger">*</span></label>
									<input type="number" name="add-device_id" id="add-device_id" class="form-control">
								</div>
								<div class="col-sm-6">
									<label for="add-name" class="col-form-label">Name<span
											class="text-danger">*</span></label>
									<input type="text" name="add-name" id="add-name" class="form-control">
								</div>
								<div class="col-sm-6">
									<label for="add-simcard" class="col-form-label">Simcard<span
											class="text-danger">*</span></label>
									<input type="number" name="add-simcard" id="add-simcard" class="form-control">
								</div>
								<div class="col-sm-6">
									<label for="add-type" class="col-form-label">Type<span
											class="text-danger">*</span></label>
									<select name="add-type" id="add-type" class="form-control" style="width:100%;">
										<option value="" selected disabled>Select Type</option>
										<option value="{{ \App\Models\Devices::TYPE_BUILT_IN }}">Built-in</option>
										<option value="{{ \App\Models\Devices::TYPE_PORTABLE }}">Portable</option>
									</select>
								</div>
								<div class="col-sm-6">
									<label for="add-protocol" class="col-form-label">Device Type</label>
									<input type="text" name="add-protocol" id="add-protocol" class="form-control">
								</div>
							</div>
						</div>
						{{-- Utilites --}}
						<div class="mb-3">
							<div class="border-bottom">
								<h6>Utilities</h6>
							</div>
							<div class="row">
								<div class="col-sm-6 col-md-3">
									<label for="add-status" class="form-label">Status<span
											class="text-danger">*</span></label>
									<div class="form-check form-switch">
										<input class="form-check-input" type="checkbox" id="add-status">
										<label class="form-check-label" for="add-status"><span class="text-dark"
												id="add-txtStatus">Inactive</span></label>
									</div>
								</div>
								<div class="col-sm-6 col-md-3">
									<div class="form-group">
										<label for="add-assigned" class="form-label">Installed ? <span
												class="text-danger">*</span></label>
										<div class="form-check form-switch">
											<input class="form-check-input" type="checkbox" id="add-assigned">
											<label class="form-check-label" for="add-assigned"><span class="text-dark"
													id="add-txtAssigned">Released</span></label>
										</div>
									</div>
									<div class="form-group vhcAssignGroup d-none">
										<label for="add-vhc_assigned" class="col-form-label">Vehicle<span
												class="text-danger">*</span></label>
										<select name="add-vhc_assigned" id="add-vhc_assigned" class="form-control"
											style="width:100%;">
											<option value="" selected disabled>Select Type</option>
											@foreach ($vhcs as $vhc)
												<option value="{{ $vhc->vid }}" data-vid="{{ $vhc->vid }}"
													data-nopol="{{ $vhc->nopol1 . ' ' . $vhc->nopol2 . ' ' . $vhc->nopol3 }}">
													{{ $vhc->nopol1 . ' ' . $vhc->nopol2 . ' ' . $vhc->nopol3 }}
												</option>
											@endforeach
										</select>
									</div>
								</div>
								<div class="col-sm-6 col-md-3">
									<div class="form-group">
										<label for="add-available" class="form-label">Available Status ? <span
												class="text-danger">*</span></label>
										<div class="form-check form-switch">
											<input class="form-check-input" type="checkbox" id="add-available">
											<label class="form-check-label" for="add-available"><span class="text-dark"
													id="add-txtAvailable">Not Available</span></label>
										</div>
									</div>
								</div>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
					<button id="btnSubmitNewDevice" type="button" class="btn btn-sm btn-danger">Submit data</button>
				</div>
			</div>
		</div>
	</div>

	<div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlUpdtDevice"
		aria-labelledby="mdlUpdtDeviceLabel" aria-hidden="true">
		<div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="mdlUpdtDeviceLabel">Edit Device</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body">
					<form>
						{{-- Primary --}}
						<div class="mb-3">
							<div class="border-bottom">
								<h6>Data Device</h6>
							</div>
							<div class="row">
								<div class="col-sm-6">
									<label for="updt-device_id" class="col-form-label">Device ID<span
											class="text-danger">*</span></label>
									<input type="number" name="updt-device_id" id="updt-device_id" class="form-control">
								</div>
								<div class="col-sm-6">
									<label for="updt-name" class="col-form-label">Name<span
											class="text-danger">*</span></label>
									<input type="text" name="updt-name" id="updt-name" class="form-control">
								</div>
								<div class="col-sm-6">
									<label for="updt-simcard" class="col-form-label">Simcard<span
											class="text-danger">*</span></label>
									<input type="number" name="updt-simcard" id="updt-simcard" class="form-control">
								</div>
								<div class="col-sm-6">
									<label for="updt-type" class="col-form-label">Type<span
											class="text-danger">*</span></label>
									<select name="updt-type" id="updt-type" class="form-control" style="width:100%;">
										<option value="" selected disabled>Select Type</option>
										<option value="{{ \App\Models\Devices::TYPE_BUILT_IN }}">Built-in</option>
										<option value="{{ \App\Models\Devices::TYPE_PORTABLE }}">Portable</option>
									</select>
								</div>
								<div class="col-sm-6">
									<label for="updt-protocol" class="col-form-label">Device Type</label>
									<input type="text" name="updt-protocol" id="updt-protocol" class="form-control">
								</div>
							</div>
						</div>
						{{-- Utilites --}}
						<div class="mb-3">
							<div class="border-bottom">
								<h6>Utilities</h6>
							</div>
							<div class="row">
								<div class="col-sm-6 col-md-3">
									<label for="updt-status" class="form-label">Status<span
											class="text-danger">*</span></label>
									<div class="form-check form-switch">
										<input class="form-check-input" type="checkbox" id="updt-status">
										<label class="form-check-label" for="updt-status"><span class="text-dark"
												id="updt-txtStatus">Inactive</span></label>
									</div>
								</div>
								<div class="col-sm-6 col-md-3">
									<div class="form-group">
										<label for="updt-assigned" class="form-label">Installed ? <span
												class="text-danger">*</span></label>
										<div class="form-check form-switch">
											<input class="form-check-input" type="checkbox" id="updt-assigned">
											<label class="form-check-label" for="updt-assigned"><span class="text-dark"
													id="updt-txtAssigned">Released</span></label>
										</div>
									</div>
									<div class="form-group vhcAssignGroup d-none">
										<label for="updt-vhc_assigned" class="col-form-label">Vehicle<span
												class="text-danger">*</span></label>
										<select name="updt-vhc_assigned" id="updt-vhc_assigned" class="form-control"
											style="width:100%;">
											<option value="" selected disabled>Select Type</option>
											@foreach ($vhcs as $vhc)
												<option value="{{ $vhc->vid }}" data-vid="{{ $vhc->vid }}"
													data-nopol="{{ $vhc->nopol1 . ' ' . $vhc->nopol2 . ' ' . $vhc->nopol3 }}">
													{{ $vhc->nopol1 . ' ' . $vhc->nopol2 . ' ' . $vhc->nopol3 }}
												</option>
											@endforeach
										</select>
									</div>
								</div>
								<div class="col-sm-6 col-md-3">
									<div class="form-group">
										<label for="updt-available" class="form-label">Available Status ? <span
												class="text-danger">*</span></label>
										<div class="form-check form-switch">
											<input class="form-check-input" type="checkbox" id="updt-available">
											<label class="form-check-label" for="updt-available"><span class="text-dark"
													id="updt-txtAvailable">Not Available</span></label>
										</div>
									</div>
								</div>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					@can('config_master_device.delete')
						<button type="button" id="btnDelDevice_updt" class="btn btn-sm btn-warning">Delete ?</button>
					@endcan
					<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
					@can('config_master_device.edit')
						<button id="btnSubmitUpdtDevices" type="button" class="btn btn-sm btn-danger">Ubah data</button>
					@endcan
				</div>
			</div>
		</div>
	</div>

	<div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDelDevice"
		aria-labelledby="mdlDelDeviceLabel" aria-hidden="true">
		<div class="modal-dialog modal-dialog-centered modal-sm">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="mdlDelDeviceLabel">Delete Device</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body">
					<div class="d-flex justify-content-center">
						<p class="mb-0">
							Kamu yakin ingin mengDelete device
							<a href="#" class="text-danger">
								<span id="del-device_id"></span>
							</a>
							?
						</p>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Close</button>
					<button id="btnSubmitDelDevice" type="button" class="btn btn-sm btn-secondary">Yes, Delete</button>
				</div>
			</div>
		</div>
	</div>
@endsection

@section('customjs')
	<script src="{{ asset('assets/js/load-image.all.min.js') }}"></script>
	<script>
		'use strict';
		const State = {
			file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
			storage_lara: "{{ asset('storage') }}/",
			stts_isact: {
				active: "{{ App\Models\Devices::IS_ACTIVE }}",
				inactive: "{{ App\Models\Devices::IS_INACTIVE }}",
			},
			stts_assigned: {
				assigned: "{{ App\Models\Devices::IS_ASSIGNED }}",
				unassigned: "{{ App\Models\Devices::IS_UNASSIGNED }}",
			},
			stts_available: {
				available: "{{ App\Models\Devices::IS_AVAIL }}",
				unavailable: "{{ App\Models\Devices::IS_UNAVAIL }}",
			},
			type: {
				built_in: "{{ App\Models\Devices::TYPE_BUILT_IN }}",
				portable: "{{ App\Models\Devices::TYPE_PORTABLE }}",
			},
			delay_typing_front: 1000,
		};

		const Wrapper = {
			activate: function () {
				Wrapper.event();
				DTable.activate();
				ANew.activate();
				AUpdt.activate();
				ADel.activate();
			},
			event: function () {
				$('#add-status').bind('change', function () {
					if ($(this).is(':checked'))
						$('#add-txtStatus').html('Active')
					else
						$('#add-txtStatus').html('Inactive')
				});
				$('#updt-status').bind('change', function () {
					if ($(this).is(':checked'))
						$('#updt-txtStatus').html('Active')
					else
						$('#updt-txtStatus').html('Inactive')
				});
				$('#add-assigned').bind('change', function () {
					if ($(this).is(':checked')) {
						$('#add-txtAssigned').html('Installed')
						$('.vhcAssignGroup').removeClass('d-none');
					} else {
						$('#add-txtAssigned').html('Released')
						$('.vhcAssignGroup').addClass('d-none');
					}
				});
				$('#updt-assigned').bind('change', function () {
					if ($(this).is(':checked')) {
						$('#updt-txtAssigned').html('Installed')
						$('.vhcAssignGroup').removeClass('d-none');
					} else {
						$('#updt-txtAssigned').html('Released')
						$('.vhcAssignGroup').addClass('d-none');
					}
				});
				$('#add-available').bind('change', function () {
					if ($(this).is(':checked'))
						$('#add-txtAvailable').html('Tersedia')
					else
						$('#add-txtAvailable').html('Not Available')
				});
				$('#updt-available').bind('change', function () {
					if ($(this).is(':checked'))
						$('#updt-txtAvailable').html('Tersedia')
					else
						$('#updt-txtAvailable').html('Not Available')
				});
				// fix modal select2
				$('#add-type').select2({
					dropdownParent: $('#mdlNewDevice'),
				});
				$('#add-vhc_assigned').select2({
					dropdownParent: $('#mdlNewDevice'),
				});
				$('#updt-type').select2({
					dropdownParent: $('#mdlUpdtDevice'),
				});
				$('#updt-vhc_assigned').select2({
					dropdownParent: $('#mdlUpdtDevice'),
				});
			},
		};

		const DTable = {
			activate: function () {
				DTable.reload();
			},
			reload: function () {
				// $('#tDevices').DataTable();
				// if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
				$('#tDevices').DataTable({
					processing: true,
					serverSide: false,
					bLengthChange: true,
					deferRender: true,
					destroy: true,
					ajax: {
						url: "{{ route('api_list_devices') }}",
						type: 'GET',
						complete: function (jqXHR, textStatus, c) {
							let count = jqXHR.responseJSON.count;
							if (typeof count != 'undefined') {
								$('#count_devices').text(count);
							}
							// removeTableSkeletonLoading()
						},
					},
					deferRender: true,
					columns: [{
						data: 'DT_RowIndex',
						className: 'text-end',
						visible: true,
						orderable: true,
						searchable: true,
					},
					{
						data: 'action',
						className: 'text-center',
						visible: true,
						orderable: true,
						searchable: true,
						render: function (data, type, row, meta) {
							let action = `
												<a href="#" class="text-decoration-none me-1 btnUpdtDevice">
													<span class="icon ion-eye fz-16"></span>
												</a>
												`;
							// <a href="#" class="text-decoration-none text-danger btnDelDevice">
							//     <span class="icon ion-trash-b fz-16"></span>
							// </a>
							return action;
						}
					},
					{
						data: 'device_id',
						className: 'text-end text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
						createdCell: function (td, cellData, rowData, row, col) {
							$(td).attr('data-id', rowData.id);
							$(td).attr('data-device_id', rowData.device_id);
							$(td).attr('data-simcard', rowData.simcard);
						},
						render: function (data, type, row, meta) {
							return `<span class="d-none">${data}</span>` + Helper.splitEvery4Char(`${data}`);
						},
					},
					{
						data: 'protocol',
						className: 'text-end text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
					},
					{
						data: 'name',
						className: 'text-end text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
					},
					{
						data: 'simcard',
						className: 'text-end text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
						render: function (data, type, row, meta) {
							return `<span class="d-none">${data}</span>` + Helper.splitEvery4Char(`${data}`);
						},
					},
					{
						data: 'type',
						className: 'text-end text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
						render: function (data, type, row, meta) {
							if (data == State.type.built_in) return 'Built-In';
							return 'Portable';
						},
					},
					{
						data: 'is_active',
						className: 'text-center text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
						render: function (data, type, row, meta) {
							if (data == State.stts_isact.active) return '<span class="badge rounded-pill bg-success">Active</span>';
							return '<span class="badge rounded-pill bg-danger">Inactive</span>';
						}
					},
					// {
					//     data: 'is_idle',
					//     className: 'text-center text-nowrap',
					//     visible: true,
					//     orderable: true,
					//     searchable: true,
					//     render: function(data, type, row, meta) {
					//         if (data == 'yes') return '<span class="badge rounded-pill bg-danger">Released</span>';
					//         return '<span class="badge rounded-pill bg-success">Installed</span>';
					//     }
					// },
					{
						data: 'is_assigned',
						className: 'text-center text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
						render: function (data, type, row, meta) {
							if (data == State.stts_assigned.assigned) {
								return '<span class="badge rounded-pill bg-success">Installed</span>'
							} else {
								return '<span class="badge rounded-pill bg-danger">Removed</span>'
							}
						}
					},
					{
						data: 'vhc_nopol1',
						className: 'text-left text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
					},
					{
						data: 'is_available',
						className: 'text-center text-nowrap',
						visible: true,
						orderable: true,
						searchable: true,
						render: function (data, type, row, meta) {
							if (data == State.stts_available.available) {
								return '<span class="badge rounded-pill bg-success">Available</span>'
							} else {
								return '<span class="badge rounded-pill bg-danger">Not Available</span>'
							}
						}
					},
					],
				});
			},
		};

		const ANew = {
			activate: function () {
				ANew.event();
			},
			event: function () {
				// modal
				$('#btnMdlNewDevice').on('click', function () {
					$('#mdlNewDevice').modal('show');
				});
				$('#mdlNewDevice').on('shown.bs.modal', function () {

				});
				// button
				$('#btnSubmitNewDevice').on('click', function () {
					let data = ANew.getData();
					ANew.submitData(data);
				});
			},
			getData: function () {
				let data = {};
				data.device_id = $('#add-device_id').val();
				data.name = $('#add-name').val();
				data.simcard = $('#add-simcard').val();
				data.type = $('#add-type').val();
				data.protocol = $('#add-protocol').val();

				if ($('#add-status').prop('checked')) {
					data.status = State.stts_isact.active;
				} else {
					data.status = State.stts_isact.inactive;
				}

				if ($('#add-assigned').prop('checked')) {
					data.assigned = State.stts_assigned.assigned;
				} else {
					data.assigned = State.stts_assigned.unassigned;
				}
				data.vid = $('#add-vhc_assigned').val();

				if ($('#add-available').prop('checked')) {
					data.available = State.stts_available.available;
				} else {
					data.available = State.stts_available.unavailable;
				}

				return data;
			},
			submitData: async function (data) {
				return new Promise((resolve, reject) => {
					if (typeof $('#btnSubmitNewDevice').attr('disabed') != 'undefined') {
						resolve({
							type: 'fail'
						});
						return false;
					}
					$('#btnSubmitNewDevice').attr('disabed', true);
					$.ajax({
						url: "{{ route('api_add_device') }}",
						method: 'POST',
						crossDomain: true,
						processData: true,
						headers: {
							'x-api-key': Helper.getCookie('_trtk'),
							'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
						},
						data: data,
						success: (data, textStatus, jqXHR) => {
							$('#btnSubmitNewDevice').removeAttr('disabed');
							if (data.meta.type != 'success') {
								resolve({
									type: 'fail'
								});
								Helper.toast('Warning', 'just now', data.meta.message);
								return false;
							}
							Helper.toast('Success', 'just now', 'success add new device');
							$('#mdlNewDevice').modal('hide');
							DTable.reload();
							resolve({
								type: 'success'
							});
						},
						error: (jqXHR, textStatus, error) => {
							$('#btnSubmitNewDevice').removeAttr('disabed');
							if (jqXHR.status >= 500) {
								Helper.toast('Error', 'just now', 'Please try again');
							} else {
								Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
									.message);
							}
							resolve({
								type: 'error'
							});
						}
					})
				})
			},
		}

		const AUpdt = {
			activate: function () {
				AUpdt.event();
			},
			event: function () {
				// modal
				$('#tDevices').on('click', '.btnUpdtDevice', async function (e) {
					let id = $(e.target).closest('tr').find('td[data-id]').data('id');
					let resp = await AUpdt.reqData({
						id
					});
					if (resp.type != 'success') {
						Helper.toast('Device Not Found', 'just now', 'please try again');
						return false;
					}
					AUpdt.passDataToView(resp.data);
				});
				$('#mdlUpdtDevice').on('shown.bs.modal', function () {

				});
				// button
				$('#btnSubmitUpdtDevices').on('click', function () {
					let data = AUpdt.getData();
					AUpdt.submitData(data);
				});
			},
			reqData: function (params) {
				return new Promise((resolve, reject) => {
					$.ajax({
						url: "{{ route('api_show_device', '') }}/" + params.id,
						method: 'GET',
						crossDomain: true,
						processData: true,
						headers: {
							'x-api-key': Helper.getCookie('_trtk'),
						},
						data: params,
						success: (data, textStatus, jqXHR) => {
							if (data.meta.type != 'success') {
								resolve({
									type: 'fail'
								});
								Helper.toast('Warning', 'just now', data.meta.message);
								return false;
							}
							resolve({
								type: 'success',
								data: data.data
							});
						},
						error: (jqXHR, textStatus, error) => {
							if (jqXHR.status >= 500) {
								Helper.toast('Error', 'just now', 'please try again');
							} else {
								Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
									.message);
							}
							resolve({
								type: 'error'
							});
						}
					})
				});
			},
			passDataToView: async function (data) {
				$('#updt-device_id').val(data.device_id);
				$('#updt-name').val(data.name);
				$('#updt-simcard').val(data.simcard);
				$('#updt-type').val(data.type).trigger('change');
				$('#updt-protocol').val(data.protocol);

				if (data.is_active == State.stts_isact.active) {
					$('#updt-status').prop('checked', true).trigger('change');
				} else {
					$('#updt-status').prop('checked', false).trigger('change');
				}

				if (data.is_assigned == State.stts_assigned.assigned) {
					$('#updt-assigned').prop('checked', true).trigger('change');
				} else {
					$('#updt-assigned').prop('checked', false).trigger('change');
				}
				let vhc_id = (data?.vhc_id) ? data?.vhc_id : '';
				if (vhc_id == 0 || vhc_id == '') { } else {
					if ($(`#updt-vhc_assigned option[value='${vhc_id}']`).length < 1) {
						$('#updt-vhc_assigned').append(`<option value="${vhc_id}}" data-vid="${vhc_id}}" data-nopol="${data.vhc_nopol1} ${data.vhc_nopol2} ${data.vhc_nopol3}</option>`);
						$('#updt-vhc_assigned').select2({
							dropdownParent: $('#mdlUpdtDevice'),
						});
					}
				}
				$('#updt-vhc_assigned').val(vhc_id).trigger('change');

				if (data.is_available == State.stts_available.available) {
					$('#updt-available').prop('checked', true).trigger('change');
				} else {
					$('#updt-available').prop('checked', false).trigger('change');
				}

				$('#mdlUpdtDevice').data('id', data.id);
				$('#mdlUpdtDevice').modal('show');
			},
			getData: function () {
				let data = {};
				data.id = $('#mdlUpdtDevice').data('id');

				data.device_id = $('#updt-device_id').val();
				data.name = $('#updt-name').val();
				data.simcard = $('#updt-simcard').val();
				data.type = $('#updt-type').val();
				data.protocol = $('#updt-protocol').val();

				if ($('#updt-status').prop('checked')) {
					data.status = State.stts_isact.active;
				} else {
					data.status = State.stts_isact.inactive;
				}

				if ($('#updt-assigned').prop('checked')) {
					data.assigned = State.stts_assigned.assigned;
				} else {
					data.assigned = State.stts_assigned.unassigned;
				}
				data.vid = $('#updt-vhc_assigned').val();

				if ($('#updt-available').prop('checked')) {
					data.available = State.stts_available.available;
				} else {
					data.available = State.stts_available.unavailable;
				}

				return data;
			},
			submitData: async function (data) {
				return new Promise((resolve, reject) => {
					if (typeof $('#btnSubmitUpdtDevices').attr('disabed') != 'undefined') {
						resolve({
							type: 'fail'
						});
						return false;
					}
					$('#btnSubmitUpdtDevices').attr('disabed', true);
					$.ajax({
						url: "{{ route('api_updt_device', '') }}/" + data.id,
						method: 'PUT',
						crossDomain: true,
						processData: true,
						headers: {
							'x-api-key': Helper.getCookie('_trtk'),
							'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
						},
						data: data,
						success: (data, textStatus, jqXHR) => {
							$('#btnSubmitUpdtDevices').removeAttr('disabed');
							if (data.meta.type != 'success') {
								resolve({
									type: 'fail'
								});
								Helper.toast('Warning', 'just now', data.meta.message);
								return false;
							}
							Helper.toast('Success', 'just now', 'success update device');
							$('#mdlUpdtDevice').modal('hide');
							DTable.reload();
							resolve({
								type: 'success'
							});
						},
						error: (jqXHR, textStatus, error) => {
							$('#btnSubmitUpdtDevices').removeAttr('disabed');
							if (jqXHR.status >= 500) {
								Helper.toast('Error', 'just now', 'Please try again');
							} else {
								Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
									.message);
							}
							resolve({
								type: 'error'
							});
						}
					})
				})
			},
		}

		const ADel = {
			activate: function () {
				ADel.event();
			},
			event: function () {
				// on table
				$('#tDevices').on('click', '.btnDelDevice', function (e) {
					let row = $(e.target).closest('tr');
					let id = row.find('td[data-id]').data('id');
					let device_id = row.find('td[data-device_id]').data('device_id');
					let simcard = row.find('td[data-simcard]').data('simcard');
					ADel.passDataToView({
						id,
						device_id,
						simcard,
					});
					$('#mdlDelDevice').data('id', id);
					$('#mdlDelDevice').modal('show');
				});
				$('#btnSubmitDelDevice').on('click', function () {
					let data = {
						id: $('#mdlDelDevice').data('id'),
					};
					ADel.submitData(data);
				});
				// on modal update
				$('#btnDelDevice_updt').on('click', function (e) {
					const {
						id,
						device_id,
						simcard
					} = AUpdt.getData();
					ADel.passDataToView({
						id,
						device_id,
						simcard,
					});
					$('#mdlDelDevice').data('id', id);
					$('#mdlDelDevice').modal('show');
				});
			},
			passDataToView: function (data) {
				$('#del-device_id').text(data.device_id);
				$('#del-simcard').text(data.simcard);
			},
			submitData: async function (data) {
				return new Promise((resolve, reject) => {
					if (typeof $('#btnSubmitDelDevice').attr('disabed') != 'undefined') {
						resolve({
							type: 'fail'
						});
						return false;
					}
					$('#btnSubmitDelDevice').attr('disabed', true);
					$.ajax({
						url: "{{ route('api_del_device', '') }}/" + data.id,
						method: 'DELETE',
						crossDomain: true,
						processData: true,
						headers: {
							'x-api-key': Helper.getCookie('_trtk'),
							'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
						},
						data: data,
						success: (data, textStatus, jqXHR) => {
							$('#btnSubmitDelDevice').removeAttr('disabed');
							if (data.meta.type != 'success') {
								resolve({
									type: 'fail'
								});
								Helper.toast('Warning', 'just now', data.meta.message);
								return false;
							}
							Helper.toast('Success', 'just now', 'success delete device');
							$('#mdlDelDevice').modal('hide');
							$('#mdlUpdtDevice').modal('hide');
							DTable.reload();
							resolve({
								type: 'success'
							});
						},
						error: (jqXHR, textStatus, error) => {
							$('#btnSubmitDelDevice').removeAttr('disabed');
							if (jqXHR.status >= 500) {
								Helper.toast('Error', 'just now', 'Please try again');
							} else {
								Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
									.message);
							}
							resolve({
								type: 'error'
							});
						}
					})
				})
			},
		}

		Wrapper.activate();
	</script>
@endsection