<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<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">
					<h1>ONU - Entry</h1>
				</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">
												<div class="input-group input-group">
													<select type="text" class="form-select" id="cboCity"></select>
												</div>
											</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;">ID No.:  </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtIDNo" disabled>
											</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;">ONU Sn No. : </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtONTSnNo">
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">MME ID: </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtMMEID">
											</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;">PPPOE Name: </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtPPPOEName">
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">PPPOE password: </label>
											<!-- <div class="col-md-1">
												<button type="button" class="btn btn-info btn-block" onclick="generatePwd()" id="btnG">G</button>	
											</div> -->
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtONTPassword">
											</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">ONT 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-responsive">
					<table class="table table-striped table-head-fixed table-bordered" id="myTable" style="max-height: 500px;">
						<thead>                  
							<tr>
								<th style="width: 3%">#</th>
								<th style="width: 15%">ID No.</th>
								<th style="width: 15%">Name</th>
								<th style="width: 15%">ONU Sn No.</th>
								<th style="width: 15%">MME ID</th>
								<th style="width: 15%">PPPOE Name</th>
								<th style="width: 15%">PPPOE password</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">ONU - Excel Import</h4>
						</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/ont/onu_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 class="modal fade modal-primary" id="myModal">
				<div class="modal-dialog" style="max-width: 40% !important;">
					<div class="modal-content" style="width: 80%; top: 29px; margin-left: 10%;">
						<div class="modal-header">
							<h4 class="modal-title">Edit</h4>
						</div>
						<div class="modal-body">
							<div class="row mb-2" style='padding-top:2%;'>
								<div class="col-md-12">
									<div class="form-group row" >
			                        	<label class="col-md-4 col-form-label" style="text-align: right;">Old ID No.:</label>
			                            <div class="col-md-5">
			                                <input type="text" class="form-control" id="txtIDNoOld" disabled>
			                            </div>
			                        </div>
									<div class="form-group row" >
			                        	<label class="col-md-4 col-form-label" style="text-align: right;">Slot ID:</label>
			                            <div class="col-md-5">
			                                <select type="text" class="form-control" id="cboSlotID" style="text-align: right;" onchange="iDNo()">
			                                	<option value=""></option>
			                                	<option value="2">2</option>
			                                	<option value="3">3</option>
			                                	<option value="4">4</option>
			                                </select>
			                            </div>
			                        </div>
			                        <div class="form-group row" >
										<label class="col-md-4 col-form-label" style="text-align: right;">Pon Port:</label>
			                            <div class="col-md-5">
			                                <select type="text" class="form-control" id="cboPonPort" style="text-align: right;" onchange="iDNo()">
			                                	<option value=""></option>
			                                	<option value="0">0</option>
			                                	<option value="1">1</option>
			                                	<option value="2">2</option>
			                                	<option value="3">3</option>
			                                	<option value="4">4</option>
			                                	<option value="5">5</option>
			                                	<option value="6">6</option>
			                                	<option value="7">7</option>
			                                	<option value="8">8</option>
			                                	<option value="9">9</option>
			                                	<option value="10">10</option>
			                                	<option value="11">11</option>
			                                	<option value="12">12</option>
			                                	<option value="13">13</option>
			                                	<option value="14">14</option>
			                                	<option value="15">15</option>
			                                </select>
			                            </div>
									</div>

									<div class="form-group row" >
										<label class="col-md-4 col-form-label" style="text-align: right;">ODB:</label>
			                            <div class="col-md-5">
			                                <select type="text" class="form-control" id="cboODB"  onchange="iDNo()">
			                                	<option value=""></option>
			                                </select>
			                            </div>
									</div>

									<div class="form-group row" >
										<label class="col-md-4 col-form-label" style="text-align: right;">Service Port:</label>
			                            <div class="col-md-5">
			                                <select type="text" class="form-control" id="cboServicePort" style="text-align: right;"  onchange="iDNo()">
			                                	<option value=""></option>
			                                </select>
			                            </div>
									</div>

									<div class="form-group row" >
			                        	<label class="col-md-4 col-form-label" style="text-align: right;">New ID No.:</label>
			                            <div class="col-md-5">
			                                <input type="text" class="form-control" id="txtIDNoNew" disabled>
			                            </div>
			                        </div>

			                        <div class="form-group row">
										<div class="col-md-6"></div>
										<div class="col-md-3">
											<button type="button" class="btn btn-success btn-block" onclick="changeIDNo();" id="btnChange">Change</button>
										</div>
									</div>

								</div>

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


		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>

var C = '<?php echo isset($_SESSION['city'])?$_SESSION['city']:""?>';
var code = '<?php echo isset($_SESSION['code'])?$_SESSION['code']:""?>';

	$(function() {
		$("body").addClass("sidebar-collapse");
		getODB();
		getServicePort();
		if(C=='Main Office'){
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "'  data-code= '" + code + "' >" + C + "</option>");	
			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;
	});

	function getODB() {
	    for (var letterCode = 'A'.charCodeAt(0); letterCode <= 'P'.charCodeAt(0); letterCode++) {
	        var letter = String.fromCharCode(letterCode);
	        for (var number = 1; number <= 8; number++) {
	            var value = letter + number;
	            $("#cboODB").append("<option value= '" + value + "'>" + value + "</option>");
	        }
	    }
	}

	function getServicePort() {
	  for (var numbers = 0; numbers <= 127; numbers++) {
	    // Use a conditional operator to add leading zero if needed
	    var formattedNumber = (numbers < 10) ? '0' + numbers : numbers;

	    // Append an option element to the dropdown list with id "cboServicePort"
	    $("#cboServicePort").append("<option value='" + formattedNumber + "'>" + formattedNumber + "</option>");
	  }
	}

	function iDNo() {
		if($("#cboSlotID").val()=="" || $("#cboPonPort").val()=="" || $("#cboODB").val()=="" || $("#cboServicePort").val()==""){
			$("#txtIDNoNew").val("");
		}else{
			$("#txtIDNoNew").val("sls@p" + $("#cboSlotID").val() + "/" +  $("#cboPonPort").val() + $("#cboODB").val() + $("#cboServicePort").val());
		}
	}

	$("#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/ont/onu_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{

			}
		}
	}));

	$("#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>");	
				}		
			});		
		});
	}


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

    function getIDNo(){
        $("#txtIDNo").val("");
        $("#txtPPPOEName").val("");
        $("#txtONTPassword").val("");
		var city= $("#cboCity").val();
        var prefix = $("#cboCity option:selected").attr("data-code");
		$.ajax({
			url: APP_URL + "api/ont/generate_id_no.php",
			type: "POST",
			data: JSON.stringify({city: city, prefix: prefix}),
		}).done(function(data) {
            $("#txtIDNo").val(data.id_no);
            $("#txtONTSnNo").val(('00000' + (parseInt(data.id_no.replace(prefix,''))+0000)).slice(-4));
            $("#txtMMEID").val(('00000' + (parseInt(data.id_no.replace(prefix,''))+0000)).slice(-4));
            $("#txtPPPOEName").val("fttx_" + ('0000' + (parseInt(data.id_no.replace(prefix,''))+0000)).slice(-4));
            $("#txtONTPassword").val("1234_" + ('0000' + (parseInt(data.id_no.replace(prefix,''))+0000)).slice(-4));
		    // $("#txtONTPassword").val("fttx_" + prefix.slice(-1) + ('00000' + (parseInt(data.id_no.replace(prefix,''))+0000)).slice(-4));
		});
	}

	function create(){ 
		var id = $("#txtID").val();
		var id_no = $("#txtIDNo").val();
		var ont_snno = $("#txtONTSnNo").val();
		var mme_id = $("#txtMMEID").val();
		var pppoe_name = $("#txtPPPOEName").val();
		var ont_password = $("#txtONTPassword").val();
		var city = $("#cboCity").val();

		if($("#txtIDNo").val().trim()==""){
			bootbox.alert("Please fill the boxes.");
		}else{
			$.ajax({
				url: APP_URL + "api/ont/create_update.php",
				type: "POST",
				data: JSON.stringify({ id: id, id_no: id_no, ont_snno: ont_snno, mme_id:mme_id, pppoe_name: pppoe_name, ont_password: ont_password, 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 ID No.");
                    getAll();
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}   
	}

	function getAll(){

		// $("#txtIDNo").val($("#cboCity option:selected").attr("data-id"));
		var city= $("#cboCity").val();
		if(city!=""){
			// getIDNo();
		}else{
			$("#txtIDNo").val("");
            $("#txtPPPOEName").val("");
		    $("#txtONTPassword").val("");
		}
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/ont/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 onclick='show(\"" + v.id_no + "\", this)' style='color: blue;cursor:pointer;'>" + v.id_no + "</td>")
					.append("<td>" + v.customer_name + "</td>")
					.append("<td>" + v.ont_snno + "</td>")
					.append("<td>" + v.mme_id + "</td>")
					.append("<td>" + v.pppoe_name + "</td>")
					.append("<td>" + v.ont_password + "</td>")
					.append("<td style='width: 70px;white-space: nowrap;'><span type='button' class='btn btn-primary btn-sm ' onclick='edit(\"" + v.id + "\", this)' style='padding: 0px 8px; min-width: 20px;' title='Edit'><i class='fas fa-edit'></i> </span> </td>")
					)
			});
		});
	}

	function show(id_no,obj){
		$("#myModal").modal('show');
		$.ajax({
			url: APP_URL + "api/installation/get_one_row_by_id_no.php",
			type: "POST",
			data: JSON.stringify({ id_no: id_no  })
		}).done(function(data) {	
			$("#txtIDNoOld").val(data.id_no);
			// $('#datePicker2').attr("data-date",data.install_date);
			// $("#txtDatePicker2").val(data.install_date);
			// $('#datePicker2').datepicker();
			// $("#txtAddress").val(data.install_address);
			// $("#txtGeolocation").val(data.geolocation);
			// $("#txtDN").val(data.dn.slice(2));
			// $("#txtSN").val(data.sn.slice(2));
			// $("#txtTechnician1").val(data.technician1);
			// $("#txtTechnician2").val(data.technician2);
			// $("#txtTechnician3").val(data.technician3);
			// $("#txtRemark").val(data.remark);

		});

	}

	function edit(id, obj){
		$("#txtIDNo").focus();

		$("#cboCity").attr("disabled", true);
		$("#txtIDNo").attr("disabled", true);
        // $("#txtIDNo1").attr("disabled", true);
		// $("#txtPPPOEName").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();
		$("#txtID").val(id);
		$("#txtIDNo").val($(tr).find("td").eq(1).text());
		// $("#txtIDNo1").val($(tr).find("td").eq(1).text().replace($("#cboCity option:selected").attr("data-id"),''));
		
		$("#txtONTSnNo").val($(tr).find("td").eq(3).text());
		$("#txtMMEID").val($(tr).find("td").eq(4).text());
		$("#txtPPPOEName").val($(tr).find("td").eq(5).text());
		$("#txtONTPassword").val($(tr).find("td").eq(6).text());
	}

	function clearForm(){
		$("#cboCity").attr("disabled", false);
		// $("#txtIDNo1").attr("disabled", false);
		$("#txtPPPOEName").attr("disabled", false);

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

		$("#txtID").val("");
		$("#txtONTSnNo").val("");
		$("#txtMMEID").val("");
		$("#txtPPPOEName").val("");
		$("#txtONTPassword").val("");
		$("#txtIDNo").val("");
        // getIDNo();
		// $("#txtIDNo").val($("#cboCity option:selected").attr("data-id"));


	}

	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/ont/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 changeIDNo(){ 
		var id_no_old = $("#txtIDNoOld").val();
		var id_no_new = $("#txtIDNoNew").val();
		var slot_id = $("#cboSlotID").val();
		var pon_port = $("#cboPonPort").val();
		var odb = $("#cboODB").val();
		var service_port = $("#cboServicePort").val();

		if($("#txtIDNoNew").val().trim()==""){
			bootbox.alert("Please fill the boxes.");
		}else{
			$.ajax({
				url: APP_URL + "api/ont/update_id_no.php",
				type: "POST",
				data: JSON.stringify({ id_no_old: id_no_old, id_no_new: id_no_new, slot_id:slot_id, pon_port: pon_port, odb: odb, service_port: service_port }),
			}).done(function(data){
				console.log(data);
				if(data.message=="updated"){
					$("#myModal").modal('hide');
					getAll();
					bootbox.alert("Successfully Updated.");
				}else if(data.message=="duplicate"){
					bootbox.alert("ID No. Aready Exit.");
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}   
	}

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

</script>
