<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<?php
	$D_ = "";
	if(isset($_GET['d'])){
		if(!empty($_GET['d'])){
			$D_ = $_GET['d'];
		}
	}
?>
<!-- <style>
	#myTable td:nth-child(2) {
	display: none
	}
</style> -->
<style>
.hiddenDiv {
    display:none;
    height: 600px;
    width: 100%;
}
iframe {
    height:inherit;
    width:inherit;
}
</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">
					<h1>Installation - Report</h1>
				</div>
				<div class="col-md-6">
				</div>
			</div>
		</div>
	</section>
	<section class="content">
		<div class="container-fluid">
			<div class="row" id="SS">
				<div class="col-md-12">
					<div class="card card-outline  card-primary">
						<div class="card-header">
							<h3 class="card-title">Search</h3>
						</div>
						<div class="overlay white" id="loading" style="display:none;position: absolute;width: 100%;height: 100%;z-index: 1000;">
							<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-6">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Date From:</label>
											<!-- &nbsp;<input id="chkDateFrom" type="checkbox" checked > -->
											<div class="col-md-8">  
												<div class="input-group">
													<div class="input-group-prepend">
														<span class="input-group-text" style="width: 40px;">
															<i class="far fa-calendar-alt"></i>
														</span>
													</div>
													<input type="text" class="form-control" id="txtDatePicker" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
												</div>
											</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-3">
												<div class="input-group input-group">
													<select type="text" class="form-control" id="cboCity"></select>
												</div>
											</div>
											<div class="col-md-2">
												<div class="input-group input-group">
													<select type="text" class="form-control" id="cboInstallType">
														<option value="">All</option>
														<option value="Cable">Cable</option>
														<option value="ONU">ONU</option>
													</select>
												</div>
											</div>
										</div>
									</div>
									<div class="col-md-6">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Date To: </label>
											<div class="col-md-8">  
												<div class="input-group">
													<div class="input-group-prepend">
														<span class="input-group-text" style="width: 40px;">
															<i class="far fa-calendar-alt"></i>
														</span>
													</div>
													<input type="text" class="form-control" id="txtDatePicker1" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
												</div>
											</div>
										</div>

										<div class="form-group row">
											<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="txtID" style="display:none;">
												<input type="text" class="form-control" id="txtIDNo">
											</div>
										</div>

										<div class="form-group row">
											<div class="col-md-6"></div>
											<div class="col-md-3">
												<button type="button" class="btn btn-primary btn-block" onclick="search()">Search</button>
											</div>
											<div class="col-md-3">
												<button type="button" id="btnExport" value=" Export Table data into Excel " datafrom="myTable" class="btn btn-success btn-block exportToExcel">Export Data</button> 
											</div>
										</div>
									</div>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>

			<div class="modal fade modal-primary" id="maps">
				<div class="modal-dialog" style="max-width: 100% !important;">
					<div class="modal-content" style="width: 54%; top: 30px; margin-left: 21%;">
						
				
							<div class="hiddenDiv"></div>

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

			<div class="modal fade modal-primary" id="myModal">
				<div class="modal-dialog" style="max-width: 100% !important;">
					<div class="modal-content" style="width: 80%; top: 29px; margin-left: 10%;">
						<div class="modal-header">
							<h4 class="modal-title">Edit</h4>
							<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>
						</div>
						<div class="modal-body">
						<div class="row mb-2" style='padding-top:2%;'>
					<div class="col-md-5">
						<div class="form-group row">
							<label class="col-md-4 col-form-label" style="text-align: right;">Install Date:</label>
							<div class="col-md-8">  
								<div class="input-group">
									<div class="input-group-prepend">
										<span class="input-group-text" style="width: 40px;">
											<i class="far fa-calendar-alt"></i>
										</span>
									</div>
									<input type="text" class="form-control" id="txtDatePicker2" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
								</div>
							</div>
						</div>
						<div class="form-group row customer_info">
							<label class="col-md-4 col-form-label" style="text-align: right;">Install Address: </label>
							<div class="col-md-8">
								<textarea type="text" class="form-control" id="txtAddress"  rows="2" ></textarea>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-md-4 col-form-label" style="text-align: right;">Geolocation:</label>
							<div class="col-md-8">
								<input type="text" class="form-control" id="txtGeolocation" >
							</div>
						</div>
						<div class="form-group row" >
							<label class="col-md-4 col-form-label" style="text-align: right;">DN: </label>
							<div class="col-md-3">
								<input type="number" class="form-control" id="txtDN" style="text-align: right;">
							</div>
							<label class="col-md-2 col-form-label" style="text-align: right;">SN: </label>
							<div class="col-md-3">
								<input type="number" class="form-control" id="txtSN" style="text-align: right;">
							</div>
						</div>
						<div class="form-group row" >
							<label class="col-md-4 col-form-label" style="text-align: right;">Technician 1: </label>
							<div class="col-md-8">
								<input type="text" class="form-control" id="txtTechnician1">
							</div>
						</div>
						<div class="form-group row" >
							<label class="col-md-4 col-form-label" style="text-align: right;">Technician 2: </label>
							<div class="col-md-8">
								<input type="text" class="form-control" id="txtTechnician2">
							</div>
						</div>
						<div class="form-group row" >
							<label class="col-md-4 col-form-label" style="text-align: right;">Technician 3: </label>
							<div class="col-md-8">
								<input type="text" class="form-control" id="txtTechnician3">
							</div>
						</div>
						<div class="form-group row customer_info">
							<label class="col-md-4 col-form-label" style="text-align: right;">Remark: </label>
							<div class="col-md-8">
								<textarea type="text" class="form-control" id="txtRemark"  rows="2" ></textarea>
							</div>
						</div>
					</div>
					<div class="col-md-6">
	
						<div class="card card-outline card-primary">
							<div class="card-header">
								<h3 class="card-title">Item List<span id="total_records1" style="font-weight:bold;"> </span> </h3>
							</div>
							<div class="card-body p-0">
								<table class="table table-striped table-responsive table-head-fixed table-bordered" id="myTable1" style="max-height: 495px;">
									<thead>                  
										<tr>
											<th style="width: 3%">#</th>
											<th style="width: 20%">Item Code</th>
											<th style="width: 42%">Item Name</th>
											<th style="width: 20%">Quantity</th>
											<th style="width: 15%">Unit</th>
											<!-- <th style="width: 5%;">Action</th> -->
										</tr>
									</thead>
									<tbody>
									</tbody>
								</table>
							</div>
						</div>

						<div class="form-group row" style="margin-bottom: 0px;">
						<div class="col-md-6"></div>
							<div class="col-md-3">
							<!-- <button type="button" class="btn btn-primary btn-block" id="btnSubmit" onclick="gotoPhotoUploader()">Photo</button> -->
							</div>
							<div class="col-md-3">
								<button type="button" class="btn btn-success btn-block" onclick="validateAndSave()">Save</button>
							</div>
						</div>				
					</div>
				</div>
						</div>
					</div>
				</div>
			</div>

			<div class="card card-outline ">
				<div class="card-header">
					<h3 class="card-title">List -&nbsp;<span id="total_records" style="font-weight:bold;"> </span></h3>
					<h3 class="card-title" style='padding-left:1000px;'> <span id="tb" 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" style="max-height: 460px; overflow:auto;">
					<table class="table table-striped table-head-fixed table-bordered" id="myTable">
						<thead style="position:sticky; top:0; background-color:#fff;">                  
							<tr></tr>
						</thead>
						<tbody></tbody>
						<tfoot style="position:sticky; bottom:0; background-color:#fff;"></tfoot>
					</table>
				</div>
			</div>	

		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>
	var D_ = '<?=$D_;?>';
	var C = '<?php echo $_SESSION['city']?>';

	var d = new Date();
	var mm = (d.getMonth("MM")+1);
	var dd = d.getDate();
	var customDate = d.getFullYear() + "-" + ((mm<10)?"0" + mm:mm) + "-" +  ((dd<10)?"0" + dd:dd);

	$(function(){

		$("body").addClass("sidebar-collapse");	
		$('#txtDatePicker, #txtDatePicker1').datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',
			showButtonPanel: true,
            showAnim: 'clip',
            autoclose: true
        }).val(customDate);
		if(C=='Main Office'){
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "'  >" + C + "</option>");	
		}

	});

	$(".exportToExcel").click(function(){
		exportExcel("#myTable");
	});

	$("#chkDateFrom").change(function(){
		if($("#chkDateFrom").prop("checked")){
			$("#txtDatePicker").attr("disabled",false);
			$("#txtDatePicker1").attr("disabled",false);
		}else{
			$("#txtDatePicker").attr("disabled",true);
			$("#txtDatePicker1").attr("disabled",true);
		}
	});

	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 search(){
		$("#loading").css("display","block");
		// var df =($("#chkDateFrom").prop("checked"))?$("#txtDatePicker").val():"";
		// var dt =($("#chkDateFrom").prop("checked"))?$("#txtDatePicker1").val():"";
		var df =$("#txtDatePicker").val();
		var dt =$("#txtDatePicker1").val();
		var id_no = $("#txtIDNo").val();
		var city = $("#cboCity").val();
		var install_type = $("#cboInstallType").val();


		$("#myTable").find("thead").find("tr").find("th").remove();
		$("#myTable").find("tbody").find("tr").remove();
		$("#myTable").find("tfoot").find("tr").remove();
		$.ajax({
			type: "POST",
			url: APP_URL + "api/installation/search.php",
			data: JSON.stringify({ df: df,dt: dt,id_no: id_no, city: city, install_type: install_type}),
			error: function(data) {
				$("#loading").css("display","none");
			}
		}).done(function(data) {	
			$("#loading").css("display","none");
			$("#myTable").find("thead tr:first").append("<th style='vertical-align:top; text-align:center;'>#</th>");	
            $("#myTable").find("thead tr:first").append("<th style='vertical-align:top; text-align:center;'>Action</th>");	
			for (var key of Object.keys(data.records[0])) {
			    $("#myTable").find("thead tr:first").append("<th style='vertical-align:top; text-align:center;'>" + key + "</th>");
			}
			$("#myTable").find('th:nth-child(4)').hide();

			$("#total_records").text(data.records.length);
			$.each(data.records, function(index) {
			    var i = 0;
			    $.each(data.records[index], function(key, value) {
					var sty = "min-width:120px;";
			    	++i;
			        if(i==1){
			        	$("#myTable").find("tbody").append("<tr><td>" + (index + 1) + "</td></tr>");
			        	// <span class='btn btn-success btn-sm fas fa-edit ' style='cursor: pointer;padding: 5px 9px 5px 10px;font-size: 14px;display:block;' onclick='edit(this)' title='Edit'></span>&nbsp;
                        $("#myTable").find("tbody tr:nth-child(" + (index + 1) + ")").append("<td class='pagination' style='min-width:51px;'><span class='btn btn-danger btn-sm fas fa-trash-alt' style='cursor: pointer;padding: 5px 9px 5px 10px;font-size: 14px;display:block;' onclick='dele(this)' title='Delete'></span>&nbsp;<span class='btn btn-primary btn-sm far fa-flag' style='cursor: pointer;padding: 5px 9px 5px 10px;font-size: 14px;display:block;' onclick='show(this)' title='Maps'></span></td>");
			        }else if(i==5){
                        
						sty = 'min-width:200px;';
					}else if(i==7){
						sty = 'min-width:300px;';
					}else if(i==12){
						sty = 'min-width:200px;';
					}else if(i>12){
						sty = 'text-align:right; padding-right:20px;min-width:100px;';
					}else{
						sty = 'min-width:150px;'
					}
			        $("#myTable").find("tbody tr:nth-child(" + (index + 1) + ")").append("<td style='" + (sty) + "'>" + value + "</td>");
			    });

				
			});		
			$("#myTable").find('td:nth-child(4)').hide();
			$("#myTable").find("tbody")
			.append($('<tr style="font-size:16px;">')
				.append("<td colspan='13' style='font-weight: bold; text-align: right;'>Total:</td>")
			);
			for (var x = 15; x <= $("#myTable tbody tr:first td").length; x++) {
				$("#myTable").find("tbody tr:last").append("<td style='font-weight: bold; text-align: right; padding-right: 20px;'>" + getTotal(x) + "</td>");
			}
       });

	}	
	
	function getTotal(num){
		var total = 0;
		$("#myTable tbody tr td:nth-child(" + num + ")").each(function(){
			total += parseInt(($(this).text())?($(this).text()):0);
		});
		return total.toLocaleString();
	}
	

	function edit(obj){
		$("#myModal").modal('show');
		var tr = $(obj).parent().parent();
		var idd = parseInt($(tr).find("td").eq(3).text());
		$("#txtID").val(idd);
		$("#myTable1").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/installation/get_one_row.php",
			type: "POST",
			data: JSON.stringify({ id: idd  })
		}).done(function(data) {	
			$('#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);

			$.each(data.s_details, function(i, v) {
				$("#myTable1").find("tbody")
				.append($('<tr>')
					.append("<td>" + (i+1) + "</td>")
					.append("<td>" + v.item_code + "</td>")
					.append("<td>" + v.item_name + "</td>")
					.append("<td><input type='number' style='text-align:right;' class='form-control' onfocus='this.select();' value='" + v.quantity + "'></td>")
					.append("<td>" + v.unit + "</td>")
				)  
			});
		});
		// alert($(tr).find("td").eq(2).text());
		// window.open(APP_URL + "entry/sales_edit.php?id=" + id  , "_blank");
	}

	function validateAndSave(){

	var item_details = [];
	$("#myTable1 tbody tr").each(function (){
		var item_detail = {
			"item_code" : ($(this).find("td").eq(1).text()),
			"item_name" : ($(this).find("td").eq(2).text()),
			"quantity" : (parseInt($(this).find("td").eq(3).find("input").val().replace(/,/g, '')))? (parseInt($(this).find("td").eq(3).find("input").val().replace(/,/g, ''))):0,
			"unit" : ($(this).find("td").eq(4).text())
		}
		item_details.push(item_detail);
	});

	var sales = {
		"id":$("#txtID").val(),
		"install_date":$("#txtDatePicker2").val(),
		"install_address":$("#txtAddress").val(),
		"geolocation":$("#txtGeolocation").val(),
		"DN":"DN" + $("#txtDN").val(),
		"SN":"SN" + $("#txtSN").val(),
		"technician1":$("#txtTechnician1").val(),
		"technician2":$("#txtTechnician2").val(),
		"technician3":$("#txtTechnician3").val(),
		"remark":$("#txtRemark").val(),
		"item_details":item_details
	};
	// if($("#txtDN").val()=="" || $("#txtSN").val()==""){
	// 	bootbox.alert("Please fill the box.");
	// }else{
		$.ajax({
			url: APP_URL + "api/installation/update.php",
			type: "POST",
			data: JSON.stringify(sales)
		}).done(function(data) {	
			if(data.message=="created"){
				gotoPhotoUploader($("#txtID").val());
				$("#myModal").modal('hide');
				search();
				// getInstallItemList();
			}else{
				bootbox.alert("Error on server side.");
			}
		});
	// }
	}

	function gotoPhotoUploader(id){
		
		bootbox.confirm({
			message: "<h4>Do u want to upload photos?</h4>",
			// message: "<h4>"+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){
					window.open("<?=$app_url;?>upload/install.php?for=install&c=" + id  , "_blank");
				}
			}
		});

		
	}



	function dele(obj){
        // bootbox for good looking 'confirm pop up'
		var tr = $(obj).parent().parent();
		var idd = parseInt($(tr).find("td").eq(3).text());
        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/installation/delete.php",
        				data: JSON.stringify({ id: idd}),
        				success: function(data){
        					if(data=="deleted"){
        						$(obj).parent().parent().remove();
        					}else{
        						bootbox.alert("Error on server side.");
        					}
        				}
        			});
        		}
        	}
        });
    }

    function show(obj){
    	$(".a").remove();
		var tr = $(obj).parent().parent();
		var idd = $(tr).find("td").eq(9).text();
	
		$("#maps").modal('show');

		    setTimeout(function () {
	        $('.hiddenDiv').show('fast', function () {
	            

	            $(this).append('<iframe class="a" frameborder="0" style="border:0"  src="https://google.com/maps?output=embed&iwloc&z=12&t=p&q='+idd+'"></iframe>');
	        });
	    }, 800);
    }



	function goToDetail(id){
		document.location = APP_URL + "entry/sales.php?id=" + id;
	}	

	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;
	}
	
</script>	
