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

<style>
  	#addCustomer{
		padding-right: 30% !important;
	}
	.hId{
		display: none;
	}
</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>Order - 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>
						</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-1"></div>
                                    <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-select" id="cboCity"></select>
                                            </div>
                                        </div>
                                        <div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Order No.:
											</label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtOrderNo" disabled>
											</div>
										</div>
                                        <div class="form-group row">
											<label for="txtDatePicker" class="col-md-4 col-form-label text-right">Order 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;">Internet Plan: </label>
											<div class="col-md-8">
												<select type="text" class="form-select" id="cboPackage">
												</select>
											</div>
							
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Month: </label>
											<div class="col-md-8">
												<select type="text" class="form-select" id="cboMonths" >
													<!-- <option value="">Months</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>
												</select>
											</div>
										</div>
										
                                    </div>
									<div class="col-md-1"></div>
                                    <div class="col-md-4">
                                    	<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Name: </label>
											<div class="col-md-8 input-group">
												<input type="text" class="form-control" id="txtCID"  disabled style="display:none;">
												<input type="text" class="form-control" id="txtName"  disabled>
												<span class="input-group-append">
													<button type="button" class="btn btn-info btn-flat" onclick="getUnsaleCustomer()">...</button>
												</span>
											</div>
										</div>
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Phone: </label>
											<div class="col-md-8 input-group">
												<input type="text" class="form-control" id="txtPhone"  disabled>
											</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">
												<input type="text" class="form-control" id="txtMemberType" disabled>
											</div>
										</div>		
										<div class="form-group row" >
											<label class="col-md-4 col-form-label" style="text-align: right;">Installation Address: </label>
											<div class="col-md-8">
												<textarea type="text" class="form-control " id="txtInstallAddress"  rows="2" disabled></textarea>
											</div>
										</div>
										<div class="form-group row" style="margin-bottom: 0px;">
											<div class="col-md-8"></div>
											<div class="col-md-4">
												<button type="button" class="btn btn-success btn-block" onclick="validateAndSave()">Save</button>
											</div>
										</div>						
									</div>
                                </div>


								<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-head-fixed table-bordered" id="myTable" style="max-height: 700px;">
											<thead>                  
												<tr>
													<th style="width: 3%">#</th>
													<th style="width: 8%">City</th>
													<th style="width: 8%">Order No.</th>
													<th style="width: 8%">Order Date</th>
													<th style="width: 6%;">Plan</th>
													<th style="width: 6%;">Month</th>
													<th style="width: 10%;">Name</th>
													<th style="width: 10%;">Phone</th>
													<th style="width: 10%;">member_type</th>
													<th style="width: 15%;">address</th>
													<th style="width: 3%;">Action</th>
												</tr>
											</thead>
											<tbody>
											</tbody>
										</table>
									</div>
								</div>

	

                                <div class="modal fade" id="addCustomer">
									<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">Customer - Entry</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">
																<div class="row">
																	<div class="col-md-5">
					
																		<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="txtCustomerEntry">
																			</div>
																		</div>
																		<div class="form-group row">
																			<label class="col-md-4 col-form-label" style="text-align: right;">Phone No.: </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>
																	<div class="col-md-1"></div>
																	<div class="col-md-5">
																		<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 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="txtAddressEntry" class="form-control" rows="2" ></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="createEntry();" id="btnSaveEntry">Add</button>
																			</div>
																		</div>
																	</div>
																</div>
															</div>						
														</div>

														<div class='col-md-12'>
															<div class="card card-outline">
																<div class="card-header">
																	<h3 class="card-title">Customer List<span  style="font-weight:bold;"> </span></h3>
																</div>
																<div class="card-body" style="margin:5px; ">
																	<table id="myTableCustomerList" class="table table-bordered table-hover">
																		<thead style="background-color: #ecedee;">
																			<tr>
																				<th style='width:5%;'>No.</th>
																				<th class="hId">CID</th>
												                                <th>Name</th>
												                                <th>Phone</th>
												                                <th>Member Type</th>
												                                <th>Address</th>
																				<th style='width:5%;'>Delete</th>
																			</tr>
																		</thead>
																		<tbody style="cursor: pointer;"></tbody>
																	</table>
																</div>
															</div>

														</div>

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


							
                            </div>
						</form>
					</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']:""?>';
    
    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 + "' data-code = '"+ code +"' >" + C + "</option>");
			getOrderNo();
			getAll();

		}
		getPackage();
		getMemberType();
	});

    $("#cboCity").change(function(){

    	$("#cboPackage").find("option").remove();
    	$("#txtOrderNo").val("");
 		if( $("#cboCity").val()){
 		    getPackage();
 			getOrderNo();
 			getAll();
 			getMemberType();
 		}	
	});

    function getOrderNo(){
		$("#txtOrderNo").val("");
		$.ajax({
			url: APP_URL + "api/order_list/get_generate_order_no.php",
			type: "POST",
            data: JSON.stringify({ code: $("#cboCity option:selected").attr('data-code')})
		}).done(function(data) {
            $("#txtOrderNo").val(data.order_no);
		});
	}

	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 getPackage(){
        $("#cboPackage").find("option").remove();
        $("#cboPackage").append("<option value= '' ></option>");
        $.ajax({
            url: APP_URL + "api/package/get_all_packages.php",
            type: "POST",
            data: JSON.stringify({ city: $("#cboCity").val()})
        }).done(function(data) {	
            $.each(data.records, function(i, v) {	
                $("#cboPackage").append("<option value= '" + v.package + "' >" + v.package + "</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>");
						
		});
	});
	}
		
	function getUnsaleCustomer(){

		// $("#loading").css("display","block");			
		var city = $("#cboCity").val();
		if(!city){
		    bootbox.alert("Please Choose City.");
		}else{
		    table = $('#myTableCustomerList').DataTable({
			"destroy": true,
			"paging": true,
			"lengthChange": true,
			"searching": true,
			"ordering": true,
			"info": true,
			"autoWidth": false,
			"responsive": true,
			"lengthMenu": [5, 50, 500, 1000, 2000],
			"pageLength": 5,
			"ajax": APP_URL + "api/customer/get_order_customer.php?city=" + city,
			"columnDefs": [
				{
					'targets': 6,
					'searchable': false,
					'orderable': false,	
					'render': function (){	
						return '<td style="text-align:center;"><span class="btn btn-danger btn-sm fas fas fa-trash-alt" style="cursor: pointer;font-size: 11px;" onclick="delCustomer(this)" title="Delete"></span></td>';	
					}
				},
				{
					className: "hId", targets: [1],
	            },
	            
				{ 
                    'searchable'    : false, 
                    'targets'       : [0,3,5] 
                },
	            ]
			
		});
		$("#addCustomer").modal('show');
		$('#myTableCustomerList').on('click', 'tbody td:not(:last-child)', function(e){


		$("#txtCID").val($(this).parent().find("td").eq(1).text());
		$("#txtName").val($(this).parent().find("td").eq(2).text());
		$("#txtPhone").val($(this).parent().find("td").eq(3).text());
		$("#txtMemberType").val($(this).parent().find("td").eq(4).text());
		$("#txtInstallAddress").val($(this).parent().find("td").eq(5).text());

			$("#addCustomer").modal('hide');
		});
		}
		

	}

	function validateAndSave(){ 
		var city = $("#cboCity").val();
		var order_no = $("#txtOrderNo").val();
		var order_date = $("#txtDatePicker").val();
		var plan = $("#cboPackage").val();
		var month = $("#cboMonths").val();

		var customer_id = $("#txtCID").val();
		var name = $("#txtName").val();
		var phone = $("#txtPhone").val();
		var member_type = $("#txtMemberType").val();
		var address = $("#txtInstallAddress").val();
		

		if(order_no.trim()=="" || name.trim()=="" || phone.trim()=="" || plan.trim()=="" ){
			bootbox.alert("Please fill the boxes.");
		}else{
			$.ajax({
				url: APP_URL + "api/order_list/create.php",
				type: "POST",
				data: JSON.stringify({ city: city, order_no: order_no, order_date: order_date, plan: plan, month:month, customer_id: customer_id, name: name, phone: phone, member_type: member_type, address: address }),
			}).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(){
		$("#myTable").find("tbody").find("tr").remove();
		var city = $("#cboCity").val();
		$.ajax({
			url: APP_URL + "api/order_list/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ city: city })
		}).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>" + v.city + "</td>")
					.append("<td>" + v.order_no + "</td>")
					.append("<td>" + v.order_date + "</td>")
					.append("<td>" + v.plan + "</td>")
					.append("<td>" + v.month + "</td>")
					.append("<td>" + v.name + "</td>")
					.append("<td>" + v.phone + "</td>")
					.append("<td>" + v.member_type + "</td>")
					.append("<td>" + v.address + "</td>")
					.append("<td style='width: 70px;white-space: nowrap;'> <span type='button' class='btn btn-danger btn-sm' onclick='del(\"" + v.id + "\",this)' style='padding: 0px 8px; min-width: 20px;' title='Delete'><i class='fas fa-trash'></i></span></td>")
				);
			});
		});
	}

	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/order_list/delete.php",
						data: JSON.stringify({ id: id }),
						success: function(data){
							if(data=="deleted"){
								getAll();
								getOrderNo();
								$(obj).parent().parent().remove();
							}else{
								bootbox.alert("Error on server side.");
							}
						}
					});
				}
			}
		});
	}
	
	function delCustomer(obj){
		$(obj).attr("disabled", false);
		var tr = $(obj).parent().parent();
		var id = $(tr).find("td").eq(1).text();

		$("#txtID").val($(tr).find("td").eq(6).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/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 createEntry(){ 
		var id = $("#txtID").val();
		var name = $("#txtCustomerEntry").val();
		var phone = $("#txtPhoneEntry1").val() + $("#txtPhoneEntry2").val();
		var member_type = $("#cboMemberType").val();
		var nrc = "";
		var address = $("#txtAddressEntry").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: "", member_type:member_type, nrc: nrc, address: address, city: city }),
			}).done(function(data){
				console.log(data);
				if(data.message=="created"){
					getUnsaleCustomer()
					clearForm();
				}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 clearForm(){

		$("#txtCID").val("");
		$("#txtName").val("");
		$("#txtPhone").val("");
		$("#txtMemberType").val("");
		$("#txtInstallAddress").val("");
		getOrderNo();
	}

</script>

