<script>
	$(document).ready(function() {
		$("#type").select2();
		$('#menu_privilege').jstree({
			"checkbox": {
				"keep_selected_style": false,
				"three_state": true
			},
			'core': {
				'check_callback': true
			},
			'plugins': ['types', 'dnd', 'checkbox'],
			'types': {
				'default': {
					'icon': 'fa fa-folder'
				},
				'html': {
					'icon': 'fa fa-file-code-o'
				},
				'svg': {
					'icon': 'fa fa-file-picture-o'
				},
				'css': {
					'icon': 'fa fa-file-code-o'
				},
				'img': {
					'icon': 'fa fa-file-image-o'
				},
				'js': {
					'icon': 'fa fa-file-text-o'
				}
			}
		});
		$('#default_access').jstree({
			'core': {
				'check_callback': true,
				'multiple': false
			},
			'plugins': ['types', 'dnd', 'checkbox'],
			'types': {
				'default': {
					'icon': 'fa fa-folder'
				},
				'html': {
					'icon': 'fa fa-file-code-o'
				},
				'svg': {
					'icon': 'fa fa-file-picture-o'
				},
				'css': {
					'icon': 'fa fa-file-code-o'
				},
				'img': {
					'icon': 'fa fa-file-image-o'
				},
				'js': {
					'icon': 'fa fa-file-text-o'
				}
			}
		});
		$('#default_access').on('select_node.jstree', function (e, data) {
            if (data.node.children.length > 0) {
                $('#default_access').jstree(true).deselect_node(data.node);                    
                $('#default_access').jstree(true).toggle_node(data.node);                    
            }
        })
		$('#formProfile').submit(function(e) {
			e.preventDefault();
		});

		backBtn.attr("href", site_url + 'settings/user');
		saveBtn.click(function() {
			let btn = $('.saveBtn').ladda();
			startLoadingButton(btn);
			swal.fire({
				title: "Apakah data sudah benar?",
				text: "Data akan di submit",
				icon: "warning",
				showCancelButton: true,
				confirmButtonText: 'Submit',
			}).then(isConfirm => {
				if (isConfirm.value) {
					var selectedMenu = [];
					var selectedMenuParent = [];
					var selectedElms = $('#menu_privilege').jstree('get_selected', true);
					var selectedElmsParent = $('#menu_privilege').jstree('get_top_selected', true);
					var defaultMenu = $('#default_access').jstree('get_selected', true);
					$.each(selectedElms, function() {
						selectedMenu.push(this.id);
					});
					$.each(selectedElms, function() {
						selectedMenuParent.push(this.parents);
					});
					$.each(selectedElmsParent, function() {
						selectedMenu.push(this.id);
					});
					var user_info = arrayToObj($('#formProfile').serializeArray());
					$.ajax({
						type: "POST",
						url: site_url + "settings/user/save",
						data: {
							...user_info,
							idOperator: '<?= $head['idOperator']; ?>',
							selectedMenu: selectedMenu,
							selectedMenuParent: selectedMenuParent,
							defaultMenu: defaultMenu
						},
						dataType: 'json',
        				// cache: false,
						// contentType: false,
						// processData: false,
						success: function(response) {
							swal.fire(response['header'] || 'success', response['message'] || '', "success").then(() => {
								window.location = site_url + "settings/user/input/" + response['idOperator'];
							});
						},
						error: function(jqXhr, textStatus, errorThrown) {
							var error_message = 'internal error';
							if (jqXhr.responseJSON !== undefined) {
								error_message = jqXhr['responseJSON']['message'];
							}
							swal.fire('error', error_message, "error");
							stopLoadingButton(btn);
						}
					});
				} else {
					stopLoadingButton(btn);
					return false;
				}
			});
		});
	});

	function saveInput(e) {}
</script>
<div class="wrapper wrapper-content animated fadeInRight">
	<div class="row">
		<div class="col-lg-12">
			<div class="ibox float-e-margins ">
				<?= form_header('7') ?>
				<div class="ibox-content">
					<div class="">
						<div class="tabs-container">
							<ul class="nav nav-tabs">
								<li class="active"><a data-toggle="tab" href="#tab-1"> User Info</a></li>
								<li class=""><a data-toggle="tab" href="#tab-2"> Menu Access</a></li>
								<li class=""><a data-toggle="tab" href="#tab-3"> Default menu Access</a></li>
							</ul>
							<form method="post" class="" id="formProfile">
								<div class="tab-content">
									<div id="tab-1" class="tab-pane active">
										<div class="panel-body">
											<div class="form-horizontal">
												<div class="form-group">
													<label class="col-sm-2 control-label">Profile Pic<br /><small class="text-navy">Max 1 File (1MB)</small></label>
													<div class="col-sm-3">
														<?php if ($head['idOperator'] == '') { ?>
															<p class="form-control-static">Silahkan simpan profile sebelum upload gambar</p>
														<?php } else { ?>
															<input id="attach-file" type="file" class="filepond" name="t_filepond" multiple data-max-file-size="1MB" data-max-files="1">
														<?php } ?>
													</div>
												</div>
												<div class="form-group">
													<input name="t_id_operator" style="display:none" type="text" value="<?= $head['idOperator'] ?>">
													<label class="col-sm-2 control-label">username</label>
													<div class="col-sm-8">
														<input name="userName" placeholder="username untuk login" <?= $head['idOperator'] ? 'readonly=""' : '' ?> type="text" class="form-control" value="<?= $head['userName'] ?>">
														<span class="help-block m-b-none"></span>
													</div>
												</div>
												<div class="form-group">
													<input name="t_id_operator" style="display:none" type="text" value="<?= $head['idOperator'] ?>">
													<label class="col-sm-2 control-label">name</label>
													<div class="col-sm-8">
														<input name="name" placeholder="nama user" type="text" class="form-control" value="<?= $head['name'] ?>">
														<span class="help-block m-b-none"></span>
													</div>
												</div>
												<div class="form-group">
													<label class="col-sm-2 control-label">email</label>
													<div class="col-sm-8">
														<input rows="2" type="text" placeholder="email" class="form-control" name="t_email" value="<?= $head['email'] ?>">
													</div>
												</div>
												<div class="form-group">
													<label class="col-sm-2 control-label">Phone</label>
													<div class="col-sm-6">
														<input maxlength="15" type="number" class="form-control" placeholder="handphone" name="t_phone" value="<?= $head['phone'] ?>">
													</div>
												</div>
												<div class="form-group hidden">
													<label class="col-sm-2 control-label">Hak akses</label>
													<div class="col-sm-4"><select class="form-control m-b" id="type" name="t_opr_type">
															<?php foreach ($operator_type as $key => $row) { ?>
																<option <?= $row['idOperatorType'] == $head['fidOperatorType'] ? 'selected' : ''; ?> value="<?= $row['idOperatorType'] ?>"><?= $row['description'] ?></option>
															<?php } ?>
														</select>
													</div>
												</div>
												<div class="form-group">
													<label class="col-sm-2 control-label">Password</label>
													<div class="col-sm-6">
														<input type="password" class="form-control" placeholder="isi untuk mengganti password" name="t_password_1">
													</div>
												</div>
												<div class="form-group">
													<label class="col-sm-2 control-label">Ulangi password</label>
													<div class="col-sm-6">
														<input type="password" class="form-control" placeholder="samakan dengan password diatas" name="t_password_2">
													</div>
												</div>
											</div>
										</div>
									</div>
									<div id="tab-2" class="tab-pane">
										<div class="panel-body">
											<div class="row" id="menu_privilege">
												<?php
												if ($head['idOperator']) {
													echo $this->menu->get_menu_privilege(0, 0, $head['idOperator'] ? $head['idOperator'] : 0);
												}
												?>
											</div>
										</div>
									</div>
									<div id="tab-3" class="tab-pane">
										<div class="panel-body">
											<div class="row" id="default_access">
												<?php
												if ($head['idOperator']) {
													echo $this->menu->get_default_access(0, 0, $head['idOperator'] ? $head['idOperator'] : 0);
												}
												?>
											</div>
										</div>
									</div>
									<div class="hr-line-dashed"></div>
									<div class="hidden" style="padding-bottom:25px">
										<div class="col-sm-4 col-sm-offset-2">
											<button class="btn btn-primary saveuserbutton" type="submit">Save </button>
										</div>
									</div>
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
	var data_files = <?php echo json_encode($images_list) ?>;
	FilePond.registerPlugin(

		FilePondPluginFileEncode,

		FilePondPluginFileValidateSize,

		FilePondPluginImageExifOrientation,

		FilePondPluginFileValidateType,

		FilePondPluginImagePreview,

		FilePondPluginFilePoster,

		FilePondPluginImageResize,

		FilePondPluginImageCrop,

		FilePondPluginImageTransform,

		FilePondPluginImageEdit,

		FilePondPluginFileRename,

	);
	pond = FilePond.create(
		document.querySelector('#attach-file'), {
			acceptedFileTypes: ['image/*'],
			files: data_files,
			server: {
				url: site_url,
				process: {
					url: "./settings/uploadImages/" + '<?= $head['idOperator'] ?>' + '/' + '1',
					method: 'post',
					dataType: 'JSON',
					withCredentials: false,
					onload: function(res) {
						console.table(res.key);
					},
					onerror: function(res, file, status) {
						console.log(res);
						return 'onerror';
					},
					ondata: function(formData) {
						console.log(formData);
						formData.append('Hello', 'World');
						return formData;
						return 'ondata';
					},
				},
			},

		}

	);

	function cleanWhiteSpace(crapURI) {
		return crapURI.replace(/[^a-zA-Z0-9-_]/g, '');

	}

	pond.setOptions({
		fileRenameFunction: (file) => new Promise(resolve => {
			var unique_time = new Date().valueOf();
			console.log(file);
			resolve(cleanWhiteSpace(file.basename + unique_time))
		}),
		maxFiles: 1,
		maxFileSize: "1MB",
		allowDrop: true,
		instantUpload: true,
		required: false,
		allowReplace: false,
		allowImageResize: true,
		allowImageCrop: true,
		allowImageEdit: true,
		imageResizeTargetWidth: 500,
		imageResizeTargetHeight: 500,
	});
	pond.on('addfile', (error, file) => {
		if (error) {
			console.log('Oh ', error);
			return;
		}
		console.log('File added', file.id);
	});
	// pond.on('addfileprogress', (file, progress) => {

	// console.log('File progres', file.id);
	// console.log('File progres bar', progres);
	// });
	pond.on('removefile', (error, file) => {
		if (error) {
			console.log('Oh no', error);
			return;
		}
		$.ajax({
			type: 'POST',
			url: site_url + "settings/removeImages/",
			data: {
				id: '<?= $head['idOperator'] ?>',
				file_id: file.id,
				file_name: file.filename,
				img_type: 1
			},
			success: function(result) {
				console.log(result);
			}
		});
		// console.log('File basename  :', file.basename);
		console.log('File Removed id :', file.id);
		console.log('File Removed filename :', file.filename);
	});
	pond.on('beforeRemoveFile', (error, file) => {
		if (error) {
			console.log('Oh no', error);
			return;
		}
		console.log('before remove File ', file);
		console.log('before remove File ', file.name);
	});

</script>