<!-- To do list ketika menambah fitur attachment -->
<!-- tambah class pk_data ke input transnum -->
<!-- buat div attachment-data untuk tempat list attachment -->
<?php if(!$ism){?>
<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<script src="<?=base_url()?>assets/js/jquery-3.1.1.min.js"></script>
	<script src="<?=base_url()?>assets/js/bootstrap.js"></script>
	<script src="<?=base_url()?>assets/js/plugins/ladda/spin.min.js"></script>
	<script src="<?=base_url()?>assets/js/plugins/ladda/ladda.min.js"></script>
	<script src="<?=base_url()?>assets/js/plugins/ladda/ladda.jquery.min.js"></script>
	<script src="<?=base_url()?>assets/js/plugins/sweetalert2/sweetalert2.min.js"></script>
</head>
<script type="text/javascript">
var list_attachment_timer;
</script>

<body>
	<?php }?>
	<div id="content">
		<div class="col-lg-12" style="margin-top: 10px;">
			<div class="ibox float-e-margins">
				<div class="text-center">
					<p class="font-bold  alert alert-success m-b-sm"><?=$attachment_description;?></p>
				</div>
				<div class="ibox-content" style="padding-bottom: 0px;">
					<form class="form-horizontal" id="submit_attachment" autocomplete="off">
						<input type="text" name="key" class="hidden form-control" value="<?=$key?>">
						<div class="form-group">
							<label class="col-sm-2 control-label">Note</label>
							<div class="col-sm-10"><input type="text" id="remark" name="remark" class="form-control"></div>
						</div>
						<div class="form-group" style="margin-bottom: 0px;"><label class="col-sm-2 control-label">Attachment</label>
							<div class="col-sm-10">
								<label class="checkbox-inline">
									<input type="file" id="userfile" name="userfile"></label>
								<label class="checkbox-inline"><button type="button" class="btn btn-xs"
										onclick="$('#userfile').val('');">x</button></label>
								<span class="help-block m-b-none">maximum 1 MB.</span>
							</div>
						</div>
						<div id="content-progress-bar" class="form-group" style="margin-bottom: 0px;display:none"><label class="col-sm-2 control-label">&nbsp;</label>
							<div class="col-sm-10">
								<div class="progress progress-striped active">
									<div id="progressBar" style="width: 0%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="0"
										role="progressbar" class="progress-bar progress-bar-danger">
										<span class="sr-only">0% Complete (success)</span>
									</div>
								</div>
							</div>
						</div>
						<div class="form-group">
							<div class="col-sm-4 col-sm-offset-2">
								<button class="processUploadAttachmentBtn btn btn-primary" type="submit">Upload file</button>
							</div>
						</div>
					</form>
				</div>
				<hr>
				<div id="result-list"></div>
				<div class="text-center <?=$token?'':'hidden';?>">
					<p class="font-bold  alert alert-warning m-b-sm" id="token_expiry_time"><?=date('Y-m-d H:i:s',strtotime($token));?></p>
				</div>
			</div>
		</div>
	</div>
	<div id="content-expire" style="display: none;">
		<div class="col-lg-12" style="margin-top: 10px;">
			<div class="alert alert-danger text-center">
				<div class="flipthis-wrapper"><a class="alert-link" href="#">Expired Upload Link</a></div>.
			</div>
		</div>
	</div>
	<script type="text/javascript">
		<?php if($token){?>
			check_expire();
			setInterval(function() { check_expire(); }, 1000);
	    if (!list_attachment_timer) {
				list_attachment_timer = setInterval(function(){list_attachment();}, 10000); 
	    }
		<?php }?>
		$('.processUploadAttachmentBtn').ladda();
		$(document).on('hide.bs.modal', function () {
	    clearInterval(list_attachment_timer); 
	    list_attachment_timer = null;
		});
		$(document).ready(function () {
			$('#submit_attachment').submit(function (e) {
				e.preventDefault();
				$.ajax({
					url: '<?=base_url()?>main/upload/upload_attachment',
					type: "post",
					data: new FormData(this),
					processData: false,
					contentType: false,
					cache: false,
					// async: false,
					xhr: function () {
						var xhr = new window.XMLHttpRequest();
						xhr.upload.addEventListener('progress', function (e) {
							if (e.lengthComputable) {
								console.log('Bytes Loaded : ' + e.loaded);
								console.log('Total Size : ' + e.total);
								console.log('Persen : ' + (e.loaded / e.total));

								var percent = Math.round((e.loaded / e.total) * 100);

								set_progress_value(percent);
							}
						});
						return xhr;
					},
					beforeSend: function (xhr) {
						set_progress_value(0);
						$('.processUploadAttachmentBtn').ladda('start');
					},
					success: function (response) {
						if (response['message']) {
							// swal.fire(response['header'] || 'success', response['message'] || '', "success").then(() => {});
							$("#remark").val("");
							$("#userfile").val("");
							list_attachment();
							set_progress_value(0);
						} else {
							set_progress_value(0);
							swal.fire('error', response, "error");
						}
						$('.processUploadAttachmentBtn').ladda('stop');
					},
					error: function (jqXhr, textStatus, errorThrown) {
						var error_message = jqXhr.responseText;
						if (jqXhr.responseJSON !== undefined) {
							error_message = jqXhr['responseJSON']['message'];
						}
						swal.fire('error', error_message, "error");
						$('.processUploadAttachmentBtn').ladda('stop');
						set_progress_value(0);
					}
				});
			});
			list_attachment();
		});

		function is_expired(state)
		{
			if(state)
			{
				$('#content').hide();
				$('#content-expire').show();
			}else{
				$('#content').show();
				$('#content-expire').hide();
			}

		}

		function check_expire()
		{
			var date_time = getDateTime();
			var start = new Date(date_time);
			var end   = new Date('<?=date('Y-m-d H:i:s',strtotime($token));?>');
			/* This gives us an integer value of the difference in seconds */
			var diff  = Math.round((end.getTime() - start.getTime()) / 1000);
			$('#token_expiry_time').text('Link akan expire dalam '+getClock(diff));
			if(diff<0)
			is_expired(1);
		}

		function getDateTime()
		{
			let date_ob = new Date();

			// adjust 0 before single digit date
			let date = ("0" + date_ob.getDate()).slice(-2);

			// current month
			let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);

			// current year
			let year = date_ob.getFullYear();

			// current hours
			let hours = date_ob.getHours();

			// current minutes
			let minutes = date_ob.getMinutes();

			// current seconds
			let seconds = date_ob.getSeconds();

			// prints date & time in YYYY-MM-DD HH:MM:SS format
			var date_time = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
			
			return date_time;
		}

		function getClock(diff) {
		    var hours = Math.floor(diff / 3600);
		    diff -= hours * 3600
		    var minutes = Math.floor(diff / 60);
		    diff -= minutes * 60;
		    var seconds = diff % 60;
		    return ('0'  + hours).slice(-2) + ":" +  ('0'  + minutes).slice(-2) + ":" + ('0'  + seconds).slice(-2);
		}

		function list_attachment() {
			$.ajax({
				url: '<?=base_url()?>main/upload/list_attachment',
				type: "post",
				dataType: 'html',
				data: {
					key: "<?=$key?>"
				},
				success: function (response) {
					$('#result-list').html(response);
					if (eval("typeof(listAttachment) == typeof(Function)")) {
						listAttachment();
					}
				}
			});
		}

		function remove_attachment(id_file) {

			swal.fire({
				title: "Buang attachment?",
				text: "File akan dihapus...",
				icon: "warning",
				showCancelButton: true,
				confirmButtonText: 'Ya',
				cancelButtonText: 'Tidak',
			}).then(isConfirm => {
				if (isConfirm.value) {
					$.ajax({
						url: '<?=base_url()?>main/upload/remove_attachment/' + id_file,
						type: "post",
						dataType: 'json',
						success: function (response) {
							if (response['message']) {
								// swal.fire(response['header'] || 'success', response['message'] || '', "success").then(() => {});
								list_attachment();
							} else {
								swal.fire('error', response, "error");
							}
						},
						error: function (jqXhr, textStatus, errorThrown) {
							var error_message = jqXhr.responseText;
							if (jqXhr.responseJSON !== undefined) {
								error_message = jqXhr['responseJSON']['message'];
							}
							swal.fire('error', error_message, "error");
						}
					});
				} else {
					return false;
				}
			});
		}

		function set_progress_value(val) {
			if(val!=0)
			{
				$('#content-progress-bar').show();
			}else{
				$('#content-progress-bar').hide();
			}
			$('#progressBar').attr('aria-valuenow', val).css('width', val + '%').text(val + '%');
		}
	</script>
	<?php if(!$ism){?>
	<link href="<?=base_url()?>assets/css/bootstrap.min.css" rel="stylesheet">
	<link href="<?=base_url()?>assets/font-awesome/css/font-awesome.css" rel="stylesheet">
	<link href="<?=base_url()?>assets/css/plugins/sweetalert2/sweetalert2.min.css" rel="stylesheet">
	<style>
		.swal2-container {
			zoom: 1.5;
		}
	</style>
</body>

</html>
<?php }?>