<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<style>
	
	.hId{
		display: none;
	}
	@media (max-width:480px){
	    .pagination{
	        display: inline-block;
	    }
	    div.dataTables_wrapper div.dataTables_filter input {
	        display: block;
	        padding-left: 0px !important;
	    }
	    .installID{
	        width: 112% !important;
	        margin-left: 14.5% !important;
	    }
	}
</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-2">
				<div class="col-md-6">
					<h3>Customer - 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-12">
					<div class="card card-outline card-primary">
						<div class="card-header">
							<h3 class="card-title">Input</h3>
								<button type="button" class="btn btn-info float-right" onclick='getExcelImportForm(this);'><i class="fas fa-plus"></i> Excel Import</button>
						</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">
							<div class="card-body">
								<div class="row">
									<div class="col-md-4">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
											<div class="col-md-8">
                                                <select type="text" class="form-control" id="cboCity"></select>
											</div>
										</div>
										<div class="form-group row">
											<input class="form-control" type="text" id="txtID" style="display:none;">
											<label class="col-md-4 col-form-label" style="text-align: right;">Name:  </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtCustomer">
											</div>
										</div>		
									</div>

									<div class="col-md-4">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Phone No. 1: </label>
											<div class="col-md-2">
												<input type="text" class="form-control" id="txtPhoneEntry1" value="09" disabled style="text-align: right;">
											</div>
											<div class="col-md-6">
												<input type="text" class="form-control" id="txtPhoneEntry2">
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Phone No. 2: </label>
											<div class="col-md-2">
												<input type="text" class="form-control" id="txtPhoneEntry3" value="09" disabled style="text-align: right;">
											</div>
											<div class="col-md-6">
												<input type="text" class="form-control" id="txtPhoneEntry4">
											</div>
										</div>		
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Member Type:</label>
											<div class="col-md-8">
												<select type="text" class="form-control" id="cboMemberType"></select>
											</div>
										</div>	
									</div>

									<div class="col-md-4">
										<!-- <div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">NRC No.: </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtNRCNo">
											</div>
										</div> -->
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Address: </label>
											<div class="col-md-8">
												<textarea type="text" id="txtAddress" class="form-control" rows="3" ></textarea>
											</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"onclick="create();" id="btnSave">Save</button>
											</div>
											<div class="col-md-4 btnEdit" 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" onclick="create()">Update</button>
											</div>
										</div>
									</div>

								</div>
							</div>
						</form>
					</div>
				</div>
			</div>

			<div class="card card-outline card-primary">
				<div class="card-header">
					<h3 class="card-title">Customer List<span  style="font-weight:bold;"> </span></h3>
				</div>
				<div class="card-body">
					<table id="myTable" class="table table-bordered table-hover" style="border-collapse: collapse !important;">
						<thead style="background-color: #ecedee;">
							<tr>
								<th style='width:5%;'>No.</th>
                                <th>Name</th>
                                <th>Phone 1</th>
                                <th>Phone 2</th>
                                <th>Member Type</th>
                                <th>Address</th>
                                <th class="hId">CID</th>
 								<th style='width:5%;'>Edit</th>
 								
								<!-- <th>Delete</th> -->
							</tr>
						</thead>
						<tbody style="cursor: pointer;"></tbody>
					</table>
				</div>
			</div>

<!-- 			<div class="card card-outline card-primary">
				<div class="card-header">
					<h3 class="card-title">Customer List<span id="total_records" style="font-weight:bold;"> </span></h3>
					<div class="card-tools">
						<span><input type="text" class="form-control" id="txtSearch" style='padding-right:0px;' placeholder='Search Here'></span>
					</div>
				</div>
				<div class="card-body p-0">
					<table class="table table-striped table-responsive table-head-fixed table-bordered" id="myTable" style="max-height: 500px;">
						<thead>                  
							<tr>
								<th style="width: 3%">#</th>
								<th style="width: 20%">Name</th>
								<th style="width: 15%">Phone</th>
								<th style="width: 15%">Member Type</th>
								<th>Address</th>
								<th style="width: 3%;">Edit</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div> -->

			<div class="modal fade" id="ExcelImportForm">
				<div class="modal-dialog" style="max-width: 50% !important;">
					<div class="modal-content installID" >
						<div class="modal-header">
							<h4 class="modal-title">Customer - Excel Import</h4>
							<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>
						</div>
						<section class="content">
							<div class="container-fluid">
								<div class="row">
									<div class="col-md-12">
										<div class="card-body">
											<form role="form" id="frmEntry">
												<div class="model-body">
													<div class="row">
														<div class="col-md-2"></div>
														<div class="col-md-8">
															<div class="form-group row" style="margin-bottom: 0px !important">
																<div class="custom-file mb-3" style="border: 1px solid #ddd; border-radius: 5px; height: 110px; color: #8f9092; text-align: center;">
															      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" class="custom-file-input" name="file" style="height: inherit; width: inherit; position: absolute; left: 0; cursor: pointer;">
															      <label id="customFile" for="customFile" style="padding-top: 40px;"><i class="fa fa-upload"></i><br>Choose a file or drag it here.</label>
															    </div>
															</div>
															<div class="form-group row" style="float: right;">
																<a href="<?=$app_url?>api/customer/customer_sample.xlsx" download><button type="button" class="btn btn-primary btn-block" id="btnDownload" style="width: 130px; margin-top: 0px; height: 38px; margin-right: 4px;"><i class="fa fa-download"></i>&nbsp; Download</button></a>
																<button type="button" class="btn btn-success btn-block" id="btnUpload" style="width: 130px; margin-top: 0px; height: 38px;"><i class="fa fa-upload"></i>&nbsp; Upload</button>
															</div>
														</div>
														<div class="col-md-2"></div>
													</div>
												</div>
											</form>
										</div>						
									</div>


								</div>
							</div>
						</section>	
					</div>
				</div>
			</div>

		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>
	var C = '<?php echo isset($_SESSION['city'])?$_SESSION['city']:""?>';

	$(function() {
		$("body").addClass("sidebar-collapse");
		if(C=='Main Office'){
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "'  >" + C + "</option>");	
			getMemberType();
			getAll();
		}

	});

$(".custom-file-input").on("change", function() {
		var fileName = $(this).val().split("\\").pop();

        if(fileName!=""){
            if(fileName.split(".")[1]=="xlsx"){
			$(this).siblings("#customFile").html(fileName);
			FN = fileName;
            }else{
                fileName = FN = "";
                $("#customFile").html("");
                $("#customFile").html('<i class="fa fa-upload"></i><br>Choose a file or drag it here.');
                bootbox.alert("Excel File Format is not correct. You should upload (XLSX) Excel File.");
            }
        }

	});

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

	$("#frmEntry").on('submit',(function(e) {
		e.preventDefault();	
		if(submitTF){	
			var formData = new FormData(this);
			if(FN){	
				bootbox.confirm({
		        	message: "<h4>Are you sure that you want to upload?</h4>",
		        	buttons: {
		        		cancel: {
		        			label: '<span class="glyphicon glyphicon-remove"></span> No',
		        			className: 'btn-danger'
		        		},
		        		confirm: {
		        			label: '<span class="glyphicon glyphicon-ok"></span> Yes',
		        			className: 'btn-primary'
		        		}
		        	},
		        	callback: function (result) {
		        		if(result){
		        			// $("#loading").css("display", "block");
		        			$.ajax({
								url: APP_URL + "api/customer/customer_upload.php",
								type:"POST",
								processData:false,
								contentType: false,
								data: formData,
								success: function(data){	
									// $("#loading").css("display", "none");
									// $("#btnUpload").attr("disabled", false);	
									if(data=="created"){
										FN = "";
										$("#frmEntry")[0].reset();
										bootbox.alert("Successfully uploaded.");
										$("#customFile").html('<i class="fa fa-upload"></i><br>Choose a file or drag it here.');
									}else if(data=="incorrect"){
										bootbox.alert("Columns are not matches! Please check again.");
									}else{
										bootbox.alert("Error on server side.");
									}
								}
							});
		        		}
		        	}
		        });
			}else{

			}
		}
	}));

	$("#txtCustomer").on("keyup", function() {
		var value = $(this).val().toLowerCase();
		$("#myTable > tbody > tr ").filter(function() {$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
		});
	});

	$("#txtPhoneEntry2").on("keyup", function() {
		var value = $(this).val().toLowerCase();
		$("#myTable > tbody > tr ").filter(function() {$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
		});
	});

	$("#txtPhoneEntry4").on("keyup", function() {
		var value = $(this).val().toLowerCase();
		$("#myTable > tbody > tr ").filter(function() {$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
		});
	});

	$("#txtSearch").on("keyup", function() {
		var value = $(this).val().toLowerCase();
		$("#myTable > tbody > tr ").filter(function() {      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
		});
	});
		
	function getAllCity(){
		$("#cboCity").find("option").remove();
		$("#cboCity").append("<option value= '' data-id = ''></option>");
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				if(v.name!='Main Office'){
					$("#cboCity").append("<option value= '" + v.name + "' data-code= '" + v.code + "' >" + v.name + "</option>");	
				}
			});		
		});
	}

	function getMemberType(){
		var city = $("#cboCity").val();
		$("#cboMemberType").find("option").remove();
		$.ajax({
			url: APP_URL + "api/member/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ city: city })
		}).done(function(data) {	
			$.each(data.records, function(i, v) {	
				$("#cboMemberType").append("<option value= '" + v.member_type + "' data-member-discount='" + v.member_discount + "' data-member-install-charges='" + v.member_install_charges + "' >" + v.member_type + "</option>");
							
			});
		});
		}	

	$("#cboCity").change(function(){
		getMemberType();
		getAll();
	});

	function create(){ 
		var id = $("#txtID").val();
		var name = $("#txtCustomer").val();
		var phone = $("#txtPhoneEntry1").val() + $("#txtPhoneEntry2").val();
		var phone2 = $("#txtPhoneEntry3").val() + $("#txtPhoneEntry4").val();
		var member_type = $("#cboMemberType").val();
		var nrc = "";
		var address = $("#txtAddress").val();
		var city = $("#cboCity").val();

		if(name.trim()=="" || phone.trim()==""){
			bootbox.alert("Please fill the boxes.");
		}else{
			$.ajax({
				url: APP_URL + "api/customer/create_update.php",
				type: "POST",
				data: JSON.stringify({ id: id, name: name, phone: phone, phone2: phone2, member_type:member_type, nrc: nrc, address: address, city: city }),
			}).done(function(data){
				console.log(data);
				if(data.message=="created"){
					bootbox.alert("Created.");
					clearForm();
					getAll();
				}else if(data.message=="updated"){
					bootbox.alert("Successfully Updated.");
					clearForm();
					getAll();
				}else if(data.message=="duplicate"){
					bootbox.alert("Duplicate data.");
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}   
	}

	// function getAll(){
	// 	var city = $("#cboCity").val();
	// 	$("#myTable").find("tbody").find("tr").remove();
	// 	$.ajax({
	// 		url: APP_URL + "api/customer/get_all_rows.php",
	// 		type: "POST",
	// 		data: JSON.stringify({ city: city }),
	// 	}).done(function(data) {
	// 		console.log(data);
	// 		$("#total_records").text("");
	// 		$.each(data.records, function(i, v) {
	// 			if(data.records){$("#total_records").text(" - " + data.records.length + " records");}else{$("#total_records").text(" - " + 0 + " record(s) found.");}
	// 			console.log(v);
	// 			$("#myTable").find("tbody")
	// 			.append($('<tr>')
	// 				.append("<td style='width: 10px'>" + (i+1) + "</td>")
	// 				.append("<td>" + v.name + "</td>")
	// 				.append("<td>" + v.phone + "</td>")
	// 				.append("<td>" + v.member_type + "</td>")
	// 				// .append("<td>" + v.nrc + "</td>")
	// 				.append("<td>" + v.address + "</td>")
	// 				.append("<td><button type='button' class='btn btn-block btn-success btn-sm fas fa-edit' onclick='edit(\"" + v.id + "\", this)' style='padding: 0px 13px;font-size: 14px; min-width: 37px'></button></td>")
	// 				// .append("<td><button type='button' class='btn btn-block btn-sm fas ' onclick='changeS(\"" + v.id + "\",\"" + v.c_status + "\", this)' style='padding: 0px 13px; font-size: 14px; min-width: 37px;'>" + v.c_status + "</button></td>")
	// 				)

	// 		});
	// 	});
	// }

		function getAll(){

			// $("#loading").css("display","block");			
			var city = $("#cboCity").val();

			table = $('#myTable').DataTable({
				"destroy": true,
				"paging": true,
				"lengthChange": true,
				"searching": true,
				"ordering": true,
				"info": true,
				"autoWidth": false,
				"responsive": true,
				"lengthMenu": [5, 50, 500, 1000, -1],
				"pageLength": 5,
				"ajax": APP_URL + "api/customer/get_all_rows.php?city=" + city,
				"columnDefs": [
					{
						'targets': 7,
						'searchable': false,
						'orderable': false,	
						'render': function (){	
							return '<td><button type="button" class="btn btn-block btn-primary btn-sm fas fa-edit" onclick="edit(this)" style="padding: 0px 13px;font-size: 14px; min-width: 37px"></button></td>';	
						}
					},
					{
						className: "hId", targets: [6],
		            },
					{ 
	                    'searchable'    : false, 
	                    'targets'       : [0,6] 
	                },
		            ]
				
			});

			// $('#myTable').on('click', 'tbody td', function(e){	


			// $("#txtCustomerID").val($(this).parent().find("td").eq(1).text());
			// $("#txtName").val($(this).parent().find("td").eq(2).text());
			// $("#txtMemberType").val($(this).parent().find("td").eq(4).text());
			// $("#txtInstallAddress").val($(this).parent().find("td").eq(6).text());
			// $("#txtMemberDiscountPercent").val($(this).parent().find("td").eq(7).text());
			// $("#txtMemberInstallDiscountPercent").val($(this).parent().find("td").eq(8).text());


			// });

		}

function changeS(id,cs,obj){
		// if(status!=0){
			// bootbox.confirm({
			// 	message: "<h4>Are you sure that you want to change status?</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){
				if(cs=="Disable"){
					var $a = 'Active';
					var $b = 'green';
					var c = 0;
				}else{
					var $a = 'Disable';
					var $b = 'red'
					var c = 1;
				}

						$.ajax({
							type: "POST",
							url: APP_URL + "api/customer/change_status.php",
							data: JSON.stringify({ id: id, c_status: c }),
							success: function(data){
								if(data.message=="updated"){
									// alert($("#myTable").parent().parent().find("td").eq(7).text());
									// $("#myTable").parent().parent().find("td").eq(7).text($a);
									$("#myTable").parent().parent().find("td").eq(7).css('color', $b);
									getAll();
									// $(obj).parent().parent().remove();
								}else{
									bootbox.alert("Error on server side.");
								}
							}
						});
			// 		}
			// 	}
			// });
		// }
	}

	function edit(obj){
		$("#txtCustomer").focus();

		// $("#txtCustomer").attr("disabled", true);
		$("#cboCity").attr("disabled", true);

		$(".btnSave").css("display", "none");
		$(".btnEdit").css("display", "block");
		$(".fa-edit").attr("disabled", true);

		$(obj).attr("disabled", false);
		var tr = $(obj).parent().parent();
		var opt = $(tr).find("td").eq(4).text();

		$("#txtID").val($(tr).find("td").eq(6).text());
		$("#txtCustomer").val($(tr).find("td").eq(1).text());
		$("#txtPhoneEntry2").val($(tr).find("td").eq(2).text().slice(2));
		$("#txtPhoneEntry4").val($(tr).find("td").eq(3).text().slice(3));
		$("#cboMemberType").val($(tr).find("td").eq(4).text());
		// $("#txtNRCNo").val($(tr).find("td").eq(4).text());
		$("#txtAddress").val($(tr).find("td").eq(5).text());
	}

	function clearForm(){

		$("#txtCustomer").attr("disabled", false);
		$("#cboCity").attr("disabled", false);

		$(".btnSave").css("display", "block");
		$(".btnEdit").css("display", "none");
		$(".fa-edit").attr("disabled", false);

		$("#txtID").val("");
		$("#txtCustomer").val("");
		// $("#txtNRCNo").val("");
		$("#txtPhoneEntry2").val("");
		$("#txtPhoneEntry4").val("");
		$("#txtAddress").val("");
		// $('#optNORMAL').attr('checked', 'checked');
	}

	function del(id,obj){
		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/customer/delete.php",
						data: JSON.stringify({ id: id }),
						success: function(data){
							if(data=="deleted"){
								getAll();
								$(obj).parent().parent().remove();
							}else{
								bootbox.alert("Error on server side.");
							}
						}
					});
				}
			}
		});
	}

		function getExcelImportForm(obj){
		$("#ExcelImportForm").modal('show');
	}
</script>
