<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<?php
$cit = "";
if(isset($_GET['city'])){
	if(!empty($_GET['city'])){
		$cit = $_GET['city'];
	}
}
?>
<?php
$dat = "";
if(isset($_GET['date'])){
	if(!empty($_GET['date'])){
		$dat = $_GET['date'];
	}
}
?>
<?php
$idn = "";
if(isset($_GET['id_no'])){
	if(!empty($_GET['id_no'])){
		$idn = $_GET['id_no'];
	}
}
?>
<?php
$cid = "";
if(isset($_GET['cid'])){
	if(!empty($_GET['cid'])){
		$cid = $_GET['cid'];
	}
}
?>
<?php
$inv = "";
if(isset($_GET['inv'])){
	if(!empty($_GET['inv'])){
		$inv = $_GET['inv'];
	}
}
?>
<style type="text/css">

	#myTable td:nth-child(2){
		width: 20%;
	}
	#myTable td:nth-child(3){
		width: 20%;
	}
	#myTable td:nth-child(4){
		width: 20%;
	}
	#myTable td:nth-child(5){
		width: 20%;
	}
	.hId{
		display: none;
	}
	#myCustomer{
		padding-right: 30% !important;
	}
	.tdDisplayNone{
		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;
	    }
	    .pagination{
	        display: inline-block;
	    }
	}
</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>Extra Days - 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;">City:</label>
												<div class="col-md-8">
													<select type="text" class="form-control" id="cboCity"></select>
												</div>
											</div>
											<div class="form-group row">
												<label for="txtDatePicker" class="col-md-4 col-form-label text-right">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="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;">ID No.: </label>
                                                <div class="col-md-6" style="padding-bottom: 2px;">
													<input type="text" class="form-control" id="txtInvoiceNo"  disabled style="display:none;">
													<input type="text" class="form-control" id="txtCustomerID"  disabled style="display:none;">
                                                    <input type="text" class="form-control" id="txtIDNo"  disabled>
                                                </div>
                                                <div class="col-md-2" style="padding-left: 6px;">
                                                    <span class="input-group-btn">
                                                        <button type="button" class="btn btn-primary" onclick="getAllCustomer()" id="btnCustomer" style="width: 100%;padding-left: 0px;"> . . . </button>
                                                    </span>   
                                                </div>
                                            </div>					
											<div class="form-group row">
												<label class="col-md-4 col-form-label" style="text-align: right;">Reason: </label>
												<div class="col-md-8">
													<div class="input-group input-group">
													<select type="text" class="form-control" id="cboReason">
														<option value="Connection Lost">Connection Lost</option>
														<!-- <option value="Suspend">Suspend</option> -->
													</select>
													</div>
												</div>
											</div>																					
											<div class="form-group row">
                                                <label class="col-md-4 col-form-label" style="text-align: right;">Days: </label>
                                                <div class="col-md-8">
                                                    <input type="number" onfocus="this.select();" class="form-control" id="txtDays"  value=0 style="text-align:right;">
                                                </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="validateAndSave();" id="btnSave">Add</button>
												</div>
											</div>
										</div>
									</div>
								</div>
							</form>
						</div>
					</div>

					<div class="modal fade" id="myCustomer">
					    <div class="modal-dialog" style="max-width: 100% !important;">
					        <div class="modal-content installID" style="width: 100%; top: 30px; margin-left: 23.5%;">
					            <div class="modal-header">
					                <!-- <h4 class="modal-title">List </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 card-outline card-primary">
					                                <div class="card-header">
					                                    <h3 class="card-title" style="font-size: 15px;">List</h3>
					                                </div>  
					                                <form role="form" id="frmEntry">
					                                    <div class="card-body">
					                                        <div class="card-body ">
					                                            <table class="table table-bordered table-hover" id="myTable" >
					                                                <thead>                  
					                                                    <tr>
					                                                        <th style="width: 3%">#</th>
																			<th>ID No.</th>
																			<th>Name</th>
																			<th>Phone</th>
																			<th>Package</th>
																			<th>CustomerID</th>
																			<th>InvoiceNo</th>
					                                                    </tr>
					                                                </thead>
					                                                <tbody>
					                                                </tbody>
					                                            </table>
					                                        </div>
					                                    </div>
					                                </form>
					                            </div>
					                        </div>
					                    </div>
					                </div>
					            </section>  
					        </div>
					    </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 class="table table-striped table-responsive table-head-fixed table-bordered" id="myTable2" style="max-height: 700px;">
								<thead>                  
									<tr>
										<th style="width: 3%">#</th>
										<th style="width: 15%">Date</th>
										<th style="width: 15%">ID No</th>
										<th style="width: 20%">Name</th>
										<th style="width: 15%">Phone</th>
										<th style="width: 20%">Reason</th>
										<th style="width: 10%">Days</th>
										<th style="width: 3%;">Action</th>
									</tr>
								</thead>
								<tbody>
								</tbody>
							</table>
						</div>
					</div>

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

	var cit = "<?=$cit;?>";
	var dat = "<?=$dat;?>";
	var idn = "<?=$idn;?>";
	var cid = "<?=$cid;?>";
	var inv = "<?=$inv;?>";

	var C = '<?= isset($_SESSION['city'])?$_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').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>");	
			getAllExtra();
		}
	});

	function getAllCustomer(){
		$("#myCustomer").modal('show');
		fillGrid();
	}

	$('#txtDatePicker').change(function() { 
		getAllExtra();
	});

	function fillGrid(){
		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, 10, 50, 100],
			"pageLength": 5,
			"ajax": APP_URL + "api/customer/get_last_sales_customer.php?city=" + city,
			'columnDefs': [	
					{
						'targets': [0, 4, 5,6],
						'searchable': false
					},
					{
						'targets': [5,6],
						"className": 'tdDisplayNone'
					}
				],
	        });

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

			$("#txtIDNo").val($(this).parent().find("td").eq(1).text());
			$("#txtCustomerID").val($(this).parent().find("td").eq(5).text());
			$("#txtInvoiceNo").val($(this).parent().find("td").eq(6).text());
			$("#myCustomer").modal('hide');
		});



	}


	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(){
		getAllExtra();
	});

	function validateAndSave(){
		$("#loading").css("display","block");
		var city = $("#cboCity").val();
		var date = $("#txtDatePicker").val();
		var id_no = $("#txtIDNo").val();
		var customer_id = $("#txtCustomerID").val();
		var invoice_no = $("#txtInvoiceNo").val();
		var reason = $("#cboReason").val();
		var days = $("#txtDays").val();

		if(id_no==""){
			bootbox.alert("Please fill ID No.");
			$("#loading").css("display","none");
			return false;
		}

		$.ajax({
			url: APP_URL + "api/extra_days/create.php",
			type: "POST",
			data: JSON.stringify({ city: city, date: date, id_no: id_no, customer_id: customer_id, invoice_no: invoice_no, reason: reason, days: days })
		}).done(function(data){	
			$("#loading").css("display","none");
			if(data.message=="created"){
				bootbox.alert("Successfully created.");
				getAllExtra();
			}else if(data.message=="duplicate"){
				bootbox.alert("Not allow duplicate package.");
			}else{
				bootbox.alert("Error on server side.");
			}
		});
	}

	function getAllExtra(){
		$("#myTable2").find("tbody").find("tr").remove();
		var city = $("#cboCity").val();
		var date = $("#txtDatePicker").val();
		$.ajax({
			url: APP_URL + "api/extra_days/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ city: city, date: date })
		}).done(function(data) {	
			$("#myTable2").find("tbody").find("tr").remove();
			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.");}
				$("#myTable2").find("tbody")
				.append($('<tr>')
					.append("<td>" + (i + 1) + "</td>")
					// .append("<td>" + v.city + "</td>")
					.append("<td>" + v.date + "</td>")
					.append("<td>" + v.id_no + "</td>")
					.append("<td>" + v.name + "</td>")
					.append("<td>" + v.phone + "</td>")
					.append("<td>" + v.reason + "</td>")
					.append("<td style='text-align:right; padding-right: 20px;'>" + v.days + "</td>")
					.append("<td style='width: 70px;white-space: nowrap;'> <span type='button' class='btn btn-danger btn-sm' onclick='del(\"" + v.id + "\",\"" + v.days + "\",\"" + v.invoice_no + "\",this)' style='padding: 0px 8px; min-width: 20px;' title='Delete'><i class='fas fa-trash'></i></span></td>")

				);
			});
		});
	}

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

	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>
