<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>

<style type="text/css">
.no-js #loader { display: none;  }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
	position: absolute;
	left: 0px;
	top: 0px;
	width: 12%;
	height: 12%;
	z-index: 9999;
	margin: 70px 45%;
	background: url(<?=$app_url;?>loading_gif/loader-64x/Preloader_2.gif) center no-repeat #fff;
}
</style>

<div class="content-wrapper" style="min-height: 1203.6px;">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<div class="container-fluid">
			<div class="row mb-12">
				<div class="col-md-6">
					<h3>City - Entry</h3>
				</div>
				<div class="col-md-6">
				</div>
			</div>
		</div>
	</section>

    <section class="content">
		<div class="container-fluid">
			<div class="row">

					<div class="col-md-4">
						<div class="card card-outline card-primary">
							<div class="card-header">
								<h3 class="card-title">Input</h3>
							</div>
							<div class="overlay white" id="loading" style="display:none;position: absolute;width: 100%;height: 100%;z-index: 10000;">
								<i class="fas fa-3x fa-sync-alt rotate360"  style="margin: 70px 45%;"></i>
							</div>
							<form role="form" id="frmEntry">
								<div class="card-body">
									<div class="row">                          
										<div class="col-md-12">
												
											<div class="form-group row">
										    	<label class="col-md-4 col-form-label" style="text-align: right;"></label>
										    	<input style="display:none" name="file" id="input-image-hidden" onchange="encodeImgtoBase64(this);" type="file" accept="image/jpeg, image/png" >
										    	<div class="col-md-8" id="imgContainer">
										    		<img src="<?=$app_url;?>/img/dummy_logo.png" style="height: 180px;">
										    	</div>
									    	</div>
									    	<div class="form-group row">
										    	<label class="col-md-4 col-form-label" style="text-align: right;"></label>
										    	<div class="col-md-8">
										    		<button type="button" class="btn btn-success" onclick="HandleBrowseClick('input-image-hidden');">Upload</button>
													<button type="button" class="btn btn-info js-main-image" id="btnCrop">Crop</button>
													<button type="button" class="btn btn-info" id="btnRecrop">Resize</button>
									    	</div>
									    </div>
	
									    	<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtCity" >
													<input type="text" class="form-control" id="txtCityID" disabled style='display:none;'>
												</div>
											</div>
											<div class="form-group row">	
												<label class="col-md-4 col-form-label" style="text-align: right;">City Code:</label>
												<div class="col-md-8">
													<input type="text" class="form-control" id="txtCode" >
												</div>
											</div>	
											<div class="form-group row">	
												<label class="col-md-4 col-form-label" style="text-align: right;">Location:</label>
												<div class="col-md-8">
													<textarea type="text" id="txtLocation" class="form-control" rows="3" ></textarea>
												</div>
											</div>		
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Invoice Remark:</label>
												<div class="col-md-8">
													<div class="input-group input-group">
														<textarea type="text" id="txtInvoiceRemark" class="form-control" rows="2" ></textarea>
													</div>
												</div>
											</div>
											<div class="form-group row">
												<div class="col-md-4"></div>
												<div class="col-md-4 btnSave"></div>
												<div class="col-md-4 btnSave">
													<button type="button" class="btn btn-success btn-block" id="btnSubmit">Save</button>
												</div>
												<div class="col-md-4 btnCancel" style="display: none;">
													<button type="button" class="btn btn-danger btn-block" onclick="clearForm()">Cancel</button>
												</div>
												<div class="col-md-4 btnEdit" style="display: none;">
													<button type="button" class="btn btn-primary btn-block" id="btnUpdate">Update</button>
												</div>
											</div>
										</div>
									</div>
								</div>
							</form>
						</div>
					</div>
		
				<div class="col-md-8">
					<div class="card card-outline card-primary">
						<div class="card-header">
							<h3 class="card-title">List<span id="total_records" style="font-weight:bold;"> </span></h3>
							<div class="card-tools">
								<button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
								<button type="button" class="btn btn-tool" data-card-widget="remove"><i class="fas fa-remove"></i></button>
							</div>
						</div>
						<div class="card-body p-0 table-responsive">
							<table class="table table-striped table-responsive table-head-fixed table-bordered" id="myTable" style="max-height: 700px;">
								<thead>                  
									<tr>
										<th style="width: 3%">#</th>
										<th style="width: 15%">Invoice Logo</th>
										<th style="width: 15%">City</th>
										<th style="width: 7%">Code</th>
										<th>Location</th>
										<th style="width: 20%">Invoice Remark</th>
										<th style="width: 15%;">Action</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>
					</div>

				</div>
				
			</div>
		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script src="../dist/js/croppie.js"></script>	
<script>


	$(function() {
		$("body").addClass("sidebar-collapse");
		getAll();

	});

	function getAll(){
		$("#myTable").find("tbody").find("tr").remove();
		
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php",
		}).done(function(data) {	
			if(data.records.length>1){
				$("#total_records").text(" - " + data.records.length + " records found.");
			}else{
				$("#total_records").text(" - " + data.records.length + " record found.");
			}
			$.each(data.records, function(i, v) {	
				if(data.records){$("#total_records").text(" - " + data.records.length + " record(s) found.");}else{$("#total_records").text(0 + " record(s) found.");}
				$("#myTable").find("tbody")
				.append($('<tr>')
					.append("<td>" + (i + 1) + "</td>")
					.append("<td><img src='<?=$app_url;?>/api/city/upload/" + v.profile_picture + "' style='width:60px;height:50px;cusor:pointer;' /></td>")
					.append("<td>" + v.name + "</td>")
					.append("<td>" + v.code + "</td>")
					.append("<td>" + v.location + "</td>")
					.append("<td>" + v.invoice_remark + "</td>")
					.append("<td><span class='btn btn-success btn-sm' style='cursor:pointer; font-size: 13px; width: 40px;' onclick='edit(\"" + v.id + "\",this)'><i class='fas fa-edit' title='edit'></i></span>&nbsp;<span class='btn btn-danger btn-sm' style='cursor:pointer; font-size: 13px; width: 40px;' onclick='del(\"" + v.id + "\",this)'><i class='fas fa-trash' title='Delete'></i></span></td>")
				);
			});
		});
	}

	function edit(id){
		$.ajax({
			url: APP_URL + "api/city/get_one_row.php",
			type: "POST",
			data: JSON.stringify({ id: id  })
		}).done(function(data) {	
			if(data.profile_picture!="" && data.profile_picture!=null){
				// if($("#previewing").length==0){
					$("#imgContainer").html('<img id="previewing" name="previewing" src="' + APP_URL + 'api/city/upload/' + data.profile_picture + '" style="height:180px; width:auto;cursor:pointer;" title="Click to Change the Photo."><img src="' + APP_URL + 'api/city/upload/' + data.profile_picture + '" id="showResult" style="display: none; height: 180px;">');
				// }
			}
			$("#txtCityID").val(data.id);
			$("#txtCity").val(data.name);
			$("#txtCode").val(data.code);
			$("#txtLocation").val(data.location);
			$("#txtInvoiceRemark").val(data.invoice_remark);
		});
			$("#txtCity").attr('disabled',true);
			$("#txtCode").attr('disabled',true);
			$(".btnSave").css("display", "none");
			$(".btnEdit").css("display", "block");
			$(".btnCancel").css("display", "block");

	}


	function del(id, obj){
        // bootbox for good looking 'confirm pop up'
        bootbox.confirm({
        	message: "<h4>Are you sure that you want to delete?</h4>",
        	buttons: {
        		confirm: {
        			label: '<span class="glyphicon glyphicon-ok"></span> Yes',
        			className: 'btn-danger'
        		},
        		cancel: {
        			label: '<span class="glyphicon glyphicon-remove"></span> No',
        			className: 'btn-primary'
        		}
        	},
        	callback: function (result) {
        		if(result){
        			$.ajax({
        				type: "POST",
        				url: APP_URL + "api/city/delete.php",
        				data: JSON.stringify({ id: id }),
        				success: function(data){
        					if(data=="deleted"){
        						$(obj).parent().parent().remove();
        					}else{
        						bootbox.alert("Error on server side.");
        					}
        				}
        			});
        		}
        	}
        });
    }
	
	function HandleBrowseClick(input_image){
		var fileinput = document.getElementById(input_image);
		fileinput.click();
	}

	$("#btnRecrop").click(function(){	
		$("#showResult").css("display", "none");
		imageCrop();
	});

	img1 = "";
	oldImg = "";
	function encodeImgtoBase64(element) {
		$("#btnCapture").css("display", "none");
		$("#btnCrop").css("display", "inline-block");
		$("#btnRecrop").css("display", "inline-block");
		$("#imgContainer").css("width", "");
		$("#imgContainer").css("height", "");
		var img = element.files[0];
		console.log(img);
		var reader = new FileReader();
		reader.onloadend = function() {
			if($("#previewing").length==0){	
				$("#imgContainer").html('<img id="previewing" name="previewing" src="<?=$app_url;?>/img/dummy_logo.png" style="height:180px; width:auto;cursor:pointer;" title="Click to Change the Photo."><img src="" id="showResult" style="display: none; height: 180px;">');
			}
			$("#showResult").attr("src", reader.result);
			$("#previewing").attr("src", reader.result);

			if(oldImg){
				$('#previewing').croppie('bind', {
				    url: reader.result
				});
			}
			oldImg = reader.result;
		}
		reader.readAsDataURL(img);
	}

	function imageCrop() {
		var mc = $('#previewing');
		if($(".croppie-container").length==0){
			mc.croppie({
				viewport: {
					width: 150,
					height: 150
				},
				boundary: {
					width: 275,
					height: 275
				},
			});
		}else{
			$(".croppie-container").css("display", "block");
		}
		$(".cr-boundary").css("margin", "0px");
		$(".cr-slider-wrap").css("margin", "8px 5px 0px 15px");
		$(".cr-slider-wrap").css("width", "65%");

		mc.on('update.croppie', function (ev, data) {
			// console.log('jquery update', ev, img);
		});
		$('.js-main-image').on('click', function (ev) {
            mc.croppie('result', {
				type: 'rawcanvas',
            	format: 'jpeg',
            	size: { width: 360, height: 360 }
            }).then(function (canvas) {	
            	$("#showResult").attr("src", canvas.toDataURL());
            	$("#showResult").css("display", "block");
				$(".croppie-container").css("display", "none");
			});
		});
	}
	$("#btnSubmit").click(function(){
		submitTF = true;
		$("#frmEntry").submit();
		submitTF = false;
	});

	$("#btnUpdate").click(function(){
		submitTF = true;
		$("#frmEntry").submit();
		submitTF = false;
	});

	$("#frmEntry").on('submit',(function(e) {
		e.preventDefault();	
		if(submitTF){			
			var formData = new FormData(this);
			var id = $("#txtCityID").val();
			var name = $("#txtCity").val();
			var code = $("#txtCode").val();
			var location = $("#txtLocation").val();
			var invoice_remark = $("#txtInvoiceRemark").val();

			if(name ==""){
				bootbox.alert("Please fill the boxes.");
			}else if(code == ""){
				bootbox.alert("Please fill the code.")
			}else{
				if($("#previewing").length==0){
					var file = APP_URL + "img/dummy_logo.png";
					formData.append("showResult", file);
				}else{
					var file = document.getElementById("showResult").src;
					formData.append("showResult", file);
				}

				var objArr = [];
				objArr.push({ "id": id, 
					"name": name, 
					"code": code, 
					"invoice_remark": invoice_remark,
					"location": location });

				formData.append('objArr', JSON.stringify( objArr ));
				$.ajax({
					url: APP_URL + "api/city/create_update.php",
					type:"POST",
					processData:false,
					contentType: false,
					data: formData,
					success: function(data){	
						$("#btnSubmit").attr("disabled", false);
						if(data.message=="created"){	
							bootbox.alert("Successfully created.");
							getAll();
							clearForm();
						}else if(data.message=="updated"){
		  					bootbox.alert("Successfully Updated.");
		  					getAll();
		  					clearForm();
		  				}else if(data.message=="duplicate"){
							bootbox.alert("Not allow duplicate entry.");
						}else{
							bootbox.alert("Error on server side.");
						}
					}
				});
			}
		}
	}));

	function clearForm(){

		$(".btnSave").css("display", "block");
		$(".btnEdit").css("display", "none");
		$(".btnCancel").css("display", "none");
		$("#txtCity").attr('disabled',false);
		$("#txtCode").attr('disabled',false);

		$("#txtCityID").val("");
		$("#txtCity").val("");
		$("#txtCode").val("");
		$("#txtInvoiceRemark").val("");
		$("#txtLocation").val("");
		$("#imgContainer").html('<img id="previewing" name="previewing" src="<?=$app_url;?>/img/dummy_logo.png" style="height:180px; width:auto;cursor:pointer;" title="Click to Change the Photo."><img src="" id="showResult" style="display: none; height: 180px;">');

	}


	function isNumber(evt) {

		evt = (evt) ? evt : window.event;
		var charCode = (evt.which) ? evt.which : evt.keyCode;
		if ( (charCode > 31 && charCode < 48) || charCode > 57) {
			return false;
		}
		return true;
	}

	function btozero(obj){
		generatePackage();
		if($(obj).val() == ""){

			$(obj).val(0);

		}

	}

</script>
