<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<?php
$id = "";
if(isset($_GET['id'])){
	if(!empty($_GET['id'])){
		$id = $_GET['id'];
	}
}
?>
<style>
	.switch {
		position: relative;
		display: inline-block;
		width: 60px;
		height: 25px;
	}
	
	/* Hide default HTML checkbox */
	.switch input {display:none;}
	
	/* The slider */
	.slider {
		position: absolute;
		cursor: pointer;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #ccc;
		-webkit-transition: .4s;
		transition: .4s;
	}
	
	.slider:before {
		position: absolute;
		content: "";
		height: 22px;
		width: 22px;
		left: 5px;
		bottom: 1px;
		background-color: white;
		-webkit-transition: .4s;
		transition: .4s;
	}
	
	input:checked + .slider {
		background-color: #2196F3;
	}
	
	input:focus + .slider {
		box-shadow: 0 0 1px #2196F3;
	}
	
	input:checked + .slider:before {
		-webkit-transform: translateX(26px);
		-ms-transform: translateX(26px);
		transform: translateX(26px);
	}
	
	/* Rounded sliders */
	.slider.round {
		border-radius: 34px;
	}
	
	.slider.round:before {
		border-radius: 50%;
	}

  	#myDV{
		padding-right: 30% !important;
	}
	#myCustomer{
		padding-right: 30% !important;
	}
	.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>Sales - 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">
                                                <input type="text" class="form-control" id="txtCity" disabled>
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">Sales Date:</label>
                                            <div class="col-md-8">  
                                                <div class="input-group input-append date" id="datePicker" data-date="2020-02-04" data-date-format="yyyy-mm-dd">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-addon input-group-text" style="width: 40px; display: table-cell;">
                                                            <i class="far fa-calendar-alt"></i>
                                                        </span>
                                                    </div>
                                                    <input type="text" class="form-control float-right" id="txtDatePicker" value="1982-06-15" >
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Invoice No.: </label>
											<div class="col-md-8">
												<input type="text" class="form-control" id="txtInvoiceNo" disabled>
											</div>
										</div>
                                        <div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Device ID No.: </label>
											<div class="col-md-8 input-group">
												<input type="text" class="form-control" id="txtIDNo" disabled>
											</div>
										</div>
										<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="txtName"  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>
									<div class="col-md-1">
									
									</div>
                                    <div class="col-md-6">
                                    	<div class="row">
                                    		<div class="col-md-12">
										<div class="form-group row">
											<label class="col-md-2 col-form-label" style="text-align: right;">Internet Plan: </label>
											<div class="col-md-6">
												<select type="text" class="form-control" id="cboPackage">
												</select>
											</div>
											<div class="col-md-3">
												<select type="text" class="form-control" 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>
											<!-- <label class="col-md-2 col-form-label" >Months</label> -->
										</div>
									</div>
									</div>
										<div class="row">
										<div class="col-md-5">
											<div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Monthly Price: </label>
												<div class="col-md-7">
													<input type="text" name="txtPackagePrice" id="txtPackagePrice" class="form-control" style="text-align: right;" value="0" disabled>
												</div>
											</div>
											<div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Installation Fee: </label>
												<div class="col-md-7">
													<input type="text" name="txtInstallationFee" id="txtInstallationFee" class="form-control" style="text-align: right;" value="0" onkeypress="return isNumber(event)" onfocus="this.select();" onkeyup="btozero(this);" >
												</div>
											</div>
											<div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Member Dis.: </label>
												<div class="col-md-7">
													<input type="text" name="txtMemberDiscount" id="txtMemberDiscount" class="form-control" style="text-align: right;" value="0" onkeypress="return isNumber(event)" onkeyup="btozero(this);calculate();" disabled> 
												</div>
											</div>
											<div class="form-group row">	
												<label class="col-md-5 col-form-label promotion" style="text-align: right;">Promotion Dis.: </label>
												<div class="col-md-7 promotion">
													<input type="text" name="txtPromotionDiscount" id="txtPromotionDiscount" class="form-control" style="text-align: right;" value="0" onkeypress="return isNumber(event)" onkeyup="btozero(this);calculate();" disabled> 
												</div>
											</div>
											<div class="form-group row">
                                                <label class="col-md-5 col-form-label" style="text-align: right;">Extra Days: </label>
                                                <div class="col-md-7">
                                                    <input type="number" onfocus="this.select();" class="form-control" id="txtDays"  value=0 style="text-align:right;">
                                                </div>
                                            </div>
										<div class="form-group row s_date" style="display:none;">
												
                                            <label class="col-md-5 col-form-label" style="text-align: right;">Start Date:</label>
                                            <div class="col-md-7">  
                                                <div class="input-group input-append date" id="datePicker1" data-date="2020-02-04" data-date-format="yyyy-mm-dd">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-addon input-group-text" style="width: 40px; display: table-cell;">
                                                            <i class="far fa-calendar-alt"></i>
                                                        </span>
                                                    </div>
                                                    <input type="text" class="form-control float-right" id="txtStartDate" value="" >
                                                </div>
                                            </div>
                                        </div>
										<div class="form-group row" style="display:none;">
											<label class="col-md-5 col-form-label " style="text-align: right;">End Date: </label>
											<div class="col-md-7 ">
                                                <input type="text" name="txtEndDate" id="txtEndDate" class="form-control " disabled >		
											</div>
										</div>
											
										</div>
										<div class="col-md-1"></div>	
										<div class="col-md-5">
											<div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Tax (%): </label>
												<div class="col-md-3">
													<input type="text" name="txtTaxCharges" id="txtTaxPercent" class="form-control" style="text-align: right;"  value=0 onfocus="this.select();" >
												</div>
												<div class="col-md-4">
													<input type="text" name="txtTaxCharges" id="txtTaxCharges" class="form-control" style="text-align: right;"  value=0 disabled>
												</div>
											</div>
											<div class="form-group row">
												<label class="col-md-5 col-form-label package_change" style="text-align: right;">Extra Charges: </label>
												<div class="col-md-7 package_change">
													<input type="text" name="txtPriceChangeCharges" id="txtPriceChangeCharges" class="form-control" style="text-align: right;"  value=0 onfocus="this.select();">
												</div>
											</div>
											<div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Normal Dis.: </label>
												<div class="col-md-7">
													<input type="text" name="txtNormalDiscount" id="txtNormalDiscount" class="form-control" style="text-align: right;" value="0" onkeypress="return isNumber(event)" onfocus="this.select();" onkeyup="btozero(this);calculate();">
												</div>
											</div>
											
											<div class="form-group row refund" style="display:none;">  
												<label class="col-md-5 col-form-label " style="text-align: right;"></label>
												<div class="col-md-7 " >
	                                                <button type="button" id="btnRefund" class="btn btn-info btn-block " onclick="refund()">Refund</button>
												</div>
											</div>

											<div class="form-group row refund" style="display:none;">	
	                                            <label class="col-md-5 col-form-label" style="text-align: right;" id="d_RefundAmount" style="display:none;">Refund Amount: </label>
												<div class="col-md-7">
													<input type="text" name="txtRefundAmount" id="txtRefundAmount" class="form-control" style="text-align: right;" disabled value="0">
												</div>
											</div>
											<div class="form-group row">	
	                                            <label class="col-md-5 col-form-label" style="text-align: right;">Total Amount: </label>
												<div class="col-md-7">
													<input type="text" name="txtTotalAmount" id="txtTotalAmount" class="form-control" style="text-align: right;" disabled value="0">
												</div>
												
											</div>
	                                        <div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Payment Type: </label>
												<div class="col-md-7">
													<select id="cboPaymentType" value='' class="form-control">
														<option value="Cash">Cash</option>
														<option value="KBZ">KBZ</option>
														<option value="KBZ Pay">KBZ Pay</option>
														<option value="AYA">AYA</option>
														<option value="CB">CB</option>
														<option value="OK$">OK$</option>
													</select>
												</div>
											</div>
											<div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Payment: </label>
												<div class="col-md-7">
													<input type="text" name="txtPayment" id="txtPayment" class="form-control" style="text-align: right;" value="0" onkeypress="return isNumber(event)" onfocus="this.select();" onkeyup="btozero(this);">
												</div>
											</div>
											<div class="form-group row">
												<label class="col-md-5 col-form-label" style="text-align: right;">Balance: </label>
												<div class="col-md-7">
													<input type="text" name="txtBalance" id="txtBalance" class="form-control" style="text-align: right;" disabled value="0" >
												</div>
											</div>
											<div class="form-group row" style="margin-bottom: 0px;">
												<div class="col-md-5"></div>
												<div class="col-md-7">
													<button type="button" class="btn btn-success btn-block" onclick="validateAndSave()">Sales</button>
												</div>
											</div>
										</div>
										<div class="col-md-1"></div>
									</div>
																		
									</div>
                                </div>

								<div class="card card-outline " id="promotion_detail" >
									<div class="card-header">
										<h3 class="card-title">Promotion List<span id="total_promotions" style="font-weight:bold;"> </span></h3>
									</div>
									<div class="card-body p-0 table-responsive">
										<table class="table table-bordered" id="myTable2">
											<thead style="background-color: #ecedee;">                  
												<tr>
													<th style="width: 3%">#</th>
													<th>Name</th>
													<th>Internet Plan </th>
													<th>Period From</th>
													<th>Period To</th>
													<th>Package(%)</th>
													<th>Fee(%)</th>
													<th>Extra Mbps</th>
													<th>Extra Days</th>
													<th>Gift</th>
													<th>Action</th>
													<!-- <th style="width: 9%;"><div class="icheck-success d-inline"><input type="checkbox" id="chkSelectAll" ><label for="chkSelectAll">All</label></div></th> -->
												</tr>
											</thead>
											<tbody>
											</tbody>
										</table>
									</div>
								</div>

								<div class="modal fade" id="myDV">
									<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">Device List<span id="total_recordsDV" style="font-weight:bold;"></span> </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-body">
																	<table id="myTableDV" class="table table-bordered table-hover" style="border-collapse: collapse !important;">
																		<thead style="background-color: #ecedee;">
																			<tr>
																				<!-- <th style="width: 3%">#</th> -->
																				<th style="width: 3%">#</th>
																				<th>ID No.</th>
																				<th>Customer Name</th>
																				<th>Phone No.</th>
																				<th>Member Type</th>
																				<th>Install Address</th>
																			</tr>
																		</thead>
																		<tbody></tbody>
																	</table>
																</div>
															</div>
														</div>
													</div>
												</div>
											</section>	
										</div>
									</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">Customer<span id="total_recordsC" style="font-weight:bold;"></span> </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-body">
																	<table id="myTable" class="table table-bordered table-hover" style="border-collapse: collapse !important;">
																		<thead style="background-color: #ecedee;">
																			<tr>
																				<th>#</th>
																				<th>ID No.</th>
																				<th>Customer Name</th>
																				<th>Phone No.</th>
																				<th>Package</th>
																				<th>Expire Date</th>
																			</tr>
																		</thead>
																		<tbody></tbody>
																	</table>
																</div>
															</div>
														</div>
													</div>
												</div>
											</section>	
										</div>
									</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-6">
					
																		<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 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-6">
																		<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="txtNRCNoEntry">
																			</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>
												</div>
											</section>	
										</div>
									</div>
								</div>

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

				<input class="form-control" type="text" id="txtID" style="display:none;">
				<input type="text" class="form-control" id="txtCustomerID"  style="display: none;">
				<input type="text" class="form-control" id="txtMemberDiscountPercent" disabled style="display:none;">
				<input type="text" class="form-control" id="txtMemberInstallDiscountPercent" disabled style="display:none;">
				<input type="text" class="form-control" id="txtCurrentMbps" disabled style="display:none;">
				<input type="text" class="form-control" id="txtCurrentDays" disabled style="display:none;">
				<input type="text" class="form-control" id="txtCurrentExpireDateNoExtra" disabled style="display:none;">
				<input type="text" class="form-control" id="txtPDExtraBandwidth"  disabled style="text-align: right;display:none;">
				<input type="text" class="form-control" id="txtPDExtraDays"  disabled style="text-align: right;display:none;">
				<input type="text" class="form-control" id="txtPDGift"  disabled style="text-align: right;display:none;">
				<input type="text" class="form-control" id="txtInvoice" disabled style="display:none;">
				<input type="text" class="form-control" id="txtCurrentBalance" disabled style="display:none;">

			</div>
		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>
	var id = "<?=$id;?>";
    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);
	$('#datePicker').attr("data-date",customDate);
	$("#txtDatePicker").val(customDate);
	$('#datePicker1').attr("data-date",customDate);
	$("#txtStartDate").val(customDate);


	$(function() {
		$(".refund").attr("style", "display:none;");
		$("#promotion_detail").attr("style", "display:none;");

		$("body").addClass("sidebar-collapse");
        $('#datePicker').datepicker();
        $('#datePicker1').datepicker();
        getOnePrint();
	});

	function getOnePrint(){
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/sales/get_one_row.php",
			type: "POST",
			data: JSON.stringify({ id: id  })
		}).done(function(data) {	
			$("#txtCity").val(data.city);
			$("#txtDatePicker").val(data.date);
			$("#txtInvoiceNo").val(data.invoice_no);
			$("#txtIDNo").val(data.id_no);
			$("#txtName").val(data.name);
			$("#txtMbps").val(data.mbps);
			$("#txtDays").val(data.months);
			$("#txtDays").val(data.days);
			$("#txtPrice").val(data.price);
			$("#txtFee").val(data.fee);
			$("#txtTaxPercent").val(data.tax);
			$("#txtTaxCharges").val(data.tax_charges);
			$("#cboPaymentType").val(data.payment_type);
			$("#txtPayment").val(data.payment);
			$("#txtDateFrom").val(data.start_date);
			$("#txtExtraDays").val(data.extra_days);
			$("#txtDateTo").val(data.end_date);
			getPackage(data.city,data.mbps,data.months);

			$('#datePicker2').attr("data-date",data.start_date);
			$("#txtDateFrom").val(data.start_date);

			$('#datePicker3').attr("data-date",data.end_date);
			$("#txtDateTo").val(data.end_date);

			$('#datePicker2').datepicker();
			$('#datePicker3').datepicker();

		});
	}


	$("#cboPackage").change(function(){
		
		$("#txtPackagePrice").val($("#cboPackage option:selected").attr("data-price"));
		if($('input[name=r1]:checked').val()=="Sales"){
			$("#txtInstallationFee").val($("#cboPackage option:selected").attr("data-fee"));
		}else if($('input[name=r1]:checked').val()=="Renew"){
			$("#txtInstallationFee").val(0);
		}
		if($("#cboMonths").val()){
			checkPromotion();
			calculate();
			// getExpireDateE();
		}

		
	});

	$("#cboMonths").on('input', function(){
		if($("#cboPackage").val()){
			checkPromotion();
			calculate();

		}
		
	});

	// $('#txtStartDate').change(function() { 
	// 	getStartDate1();
	// });

	$('#txtDatePicker').change(function() { 
		clearDate();
		getPackage();

	});

	$("#txtInstallationFee").on('input', function(){
		calculate();
	});
	
	$("#txtNormalDiscount").on('input', function(){
		calculate();
	});

	$("#txtPriceChangeCharges").on('input', function(){
		calculate();
	});

	$("#txtPayment").on('input', function(){
		calculate();
	});

	$("#txtTaxPercent").on('input', function(){
		calculate();
	});

	function changeCWS(){
			var extra_mbps = 0;
			var extra_days = 0;
			var pd_gift = "";
			$("#myTable2 tbody tr").each(function(){
				if($(this).find(".chkOnOff").prop("checked")){
					extra_mbps += parseInt($(this).find("td").eq(7).text());
					extra_days += parseInt($(this).find("td").eq(8).text());
					pd_gift += $(this).find("td").eq(9).text();
				}
			});
			$("#txtPDExtraBandwidth").val(extra_mbps);
			$("#txtPDExtraDays").val(extra_days);
			$("#txtPDGift").val(pd_gift);
			getStartDate();
			calculate();
	}

	function getMemberType(){
		$("#cboMemberType").find("option").remove();
		$.ajax({
			url: APP_URL + "api/member/get_all_rows.php",
			type: "POST",
			data: JSON.stringify({ city: $("#cboCity").val() })
		}).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 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(c,m,d){

	$("#cboPackage").find("option").remove();
	$("#txtPackageName").val("");
	$("#cboPackage").append("<option value= '' data-price='" + 0 + "'></option>");
	$.ajax({
		url: APP_URL + "api/package/get_all_packages_price_change.php",
		type: "POST",
		data: JSON.stringify({ city: $("#txtCity").val(), pcd:$("#txtDatePicker").val() })
	}).done(function(data) {	
		$.each(data.records, function(i, v) {	
			$("#cboPackage").append("<option value= '" + v.package + "' data-fee='" + v.fee + "' data-mbps='" + v.mbps + "' data-days='" + v.days + "' data-price='" + v.package_price + "' >" + v.package + "</option>");
						
		});
		$("#cboPackage").val(m+'MB');
		$("#cboMonths").val(d);


	});
	}		

    function checkPromotion(){
        var city = $("#cboCity").val();
        var date = $("#txtDatePicker").val();
        var package = $("#cboPackage").val();
        var months = $("#cboMonths").val();
        $("#myTable2").find("tbody").find("tr").remove();
        $.ajax({
            url: APP_URL + "api/promotion/get_promotion.php",
            type: "POST",
            data: JSON.stringify({ city: city, date: date, package: package, months: months })
        }).done(function(data){

        	if(data.records.length>0){
            $("#promotion_detail").removeAttr("style", "display:none;");
            $("#pd_charges").removeAttr("style", "display:none;");
            $('html, body').animate({
                scrollTop: $("#promotion_detail").offset().top
            }, 500);

            $.each(data.records, function(i, v) {
                console.log(v);
            $("#myTable2").find("tbody")
                .append($('<tr>')
                    .append("<td style='width: 10px'>" + (i+1) + "</td>")
                    .append("<td>" + v.name + "</td>")
                    .append("<td>" + v.package + "</td>")
                    .append("<td>" + v.period_from + "</td>")
                    .append("<td>" + v.period_to + "</td>")
                    .append("<td style='text-align:right;'>" + v.package_price + "</td>")
                    .append("<td style='text-align:right;'>" + v.installation_fees + "</td>")
                    .append("<td style='text-align:right;'>" + v.bandwidth + "</td>")
                    .append("<td style='text-align:right;'>" + v.extra_days + "</td>")
                    .append("<td>" + v.gift + "</td>")
                    .append("<td style='display:none;'>" + v.id + "</td>")
                    .append("<td><label class='switch'><input type='checkbox' class='chkOnOff' onclick='changeCWS()'  checked><span class='slider round'></span></label></td>")
                )
            });
            CKPromotion = "Yes";
            changeCWS();

			}else{
				$("#promotion_detail").attr("style", "display:none;");
				$("#pd_charges").attr("style", "display:none;");

				$("#txtPDExtraBandwidth").val(0);
				$("#txtPDExtraDays").val(0);
				$("#txtPDGift").val("");

				CKPromotion = "No";
				getStartDate();
			}
            calculate();

        });
    }	

	function getStartDate(){

		if($("#txtRefundAmount").val()==0){
			var select_date = $("#txtStartDate").val();
			var days = $("#cboMonths option:selected").val();
			var extra = $("#txtPDExtraDays").val();

			if($('input[name=r1]:checked').val()=="Sales"){
					$.ajax({
						url: APP_URL + "api/sales/compare_date.php",
						type: "POST",
						data: JSON.stringify({ select_date: select_date, days:days, extra:extra, current_expire_date:""})
					}).done(function(data) {	

						$("#txtStartDate").val(data.start_date);
						$("#txtEndDate").val(data.end_date);
					});
			}else if($('input[name=r1]:checked').val()=="Renew"){
				var current_expire_date = $("#txtCurrentExpireDate").val();
				var sales_date = $("#txtDatePicker").val();
					if(new Date(current_expire_date) < sales_date){
				}else{
					$(".refund").removeAttr("style", "display:none;");
				}

				$.ajax({
					url: APP_URL + "api/sales/compare_date.php",
					type: "POST",
					data: JSON.stringify({ select_date: select_date, current_expire_date: current_expire_date, days:days, extra:extra, sales_date: sales_date})
				}).done(function(data) {	
					$('#datePicker1').attr("data-date",data.start_date);
					$("#txtStartDate").val(data.start_date);
					$('#datePicker1').datepicker();
					$("#txtEndDate").val(data.end_date);

				});

			}
		}
		// else{
		// 	getStartDate();
		// }

	}

	function refund(){
		if($("#btnRefund").html()=="Refund"){
			CKRefund = "Yes";
			var invoice_no = $("#txtInvoice").val();
			var id_no = $("#txtIDNo").val();
			var customer_id = $("#txtCustomerID").val();
			var date = $("#txtDatePicker").val();
			$("#start_date").removeAttr("style", "display:none;");
				$.ajax({
					url: APP_URL + "api/sales/get_refund_amount.php",
					type: "POST",
					data: JSON.stringify({ invoice_no:invoice_no, id_no: id_no, customer_id: customer_id, date: date})
				}).done(function(data) {	
					$("#txtRefundAmount").val(data);
					$("#txtStartDate").val($("#txtDatePicker").val());
					$("#txtPriceChangeCharges").val(0);
					// getExpireDateE();
					calculate();
				});
				$("#btnRefund").html("Cancel Refund");
				$(".refund").removeAttr("style", "display:none;");
		}else{
			CKRefund = "No";
			$("#txtRefundAmount").val(0);
			$("#txtPriceChangeCharges").val(0);
			$("#txtTotalAmount").val(0);
			getStartDate();
			calculate();
			$("#btnRefund").html("Refund");
			// $(".refund").attr("style", "display:none;");
		}
	}

	function calculate(){
		var current_bal = (parseInt($("#txtCurrentBalance").val().replace(/,/g, '')))? (parseInt($("#txtCurrentBalance").val().replace(/,/g, ''))):0;
		var package_price = ((parseInt($("#cboMonths").val().replace(/,/g, '')))? (parseInt($("#cboMonths").val().replace(/,/g, ''))):0) * ((parseInt($("#txtPackagePrice").val().replace(/,/g, '')))? (parseInt($("#txtPackagePrice").val().replace(/,/g, ''))):0);
		var fee = (parseInt($("#txtInstallationFee").val().replace(/,/g, '')))? (parseInt($("#txtInstallationFee").val().replace(/,/g, ''))):0;
		var tax_percent = (parseInt($("#txtTaxPercent").val().replace(/,/g, '')))? (parseInt($("#txtTaxPercent").val().replace(/,/g, ''))):0;
		var tax = package_price*tax_percent/100;
		$("#txtTaxCharges").val(tax.toLocaleString());

		var total_package_discount = 0;
		var total_fee_discount = 0;
		$("#myTable2 tbody tr").each(function(){
			if($(this).find(".chkOnOff").prop("checked")){
				total_package_discount += parseInt($(this).find("td").eq(5).text());
				total_fee_discount += parseInt($(this).find("td").eq(6).text());
			}
		});

		var promo_p_dis = total_package_discount * package_price / 100 ;
		var promo_fee_dis = total_fee_discount * fee / 100 ;

		$("#txtPromotionDiscount").val((promo_p_dis+promo_fee_dis).toLocaleString());
		var normal_discount = (parseInt($("#txtNormalDiscount").val().replace(/,/g, '')))? (parseInt($("#txtNormalDiscount").val().replace(/,/g, ''))):0;
		var mdp = (parseInt($("#txtMemberDiscountPercent").val().replace(/,/g, '')))? (parseInt($("#txtMemberDiscountPercent").val().replace(/,/g, ''))):0;
		var midp = (parseInt($("#txtMemberInstallDiscountPercent").val().replace(/,/g, '')))? (parseInt($("#txtMemberInstallDiscountPercent").val().replace(/,/g, ''))):0;
		var member_discount = (package_price * mdp /100) + (fee * midp /100);
		$("#txtMemberDiscount").val(member_discount.toLocaleString());
		var promotion_discount = (parseInt($("#txtPromotionDiscount").val().replace(/,/g, '')))? (parseInt($("#txtPromotionDiscount").val().replace(/,/g, ''))):0;
		var refund_amount = (parseInt($("#txtRefundAmount").val().replace(/,/g, '')))? (parseInt($("#txtRefundAmount").val().replace(/,/g, ''))):0; 
		var price_change_charges = (parseInt($("#txtPriceChangeCharges").val().replace(/,/g, '')))? (parseInt($("#txtPriceChangeCharges").val().replace(/,/g, ''))):0;
		var total_amount = current_bal+package_price+fee+tax-normal_discount-member_discount-promotion_discount-refund_amount+price_change_charges;
		$("#txtTotalAmount").val(total_amount.toLocaleString());
		var payment = (parseInt($("#txtPayment").val().replace(/,/g, '')))? (parseInt($("#txtPayment").val().replace(/,/g, ''))):0;
		$("#txtBalance").val((total_amount-payment).toLocaleString());

	}

	function validateAndSave(){
		var details = [];
		$("#myTable2 tbody tr td input[type='checkbox']").each(function (){
			var ischecked = $(this).is(":checked");
			if(ischecked){
				var detail = {
					"package_percent" : $(this).parent().parent().parent().find("td").eq(5).text(),
					"fee_percent" : $(this).parent().parent().parent().find("td").eq(6).text(),
					"mbps" : $(this).parent().parent().parent().find("td").eq(7).text(),
					"days" : $(this).parent().parent().parent().find("td").eq(8).text(),
					"gift" : $(this).parent().parent().parent().find("td").eq(9).text(),
					"pid" : $(this).parent().parent().parent().find("td").eq(10).text()
				}
				details.push(detail);
			}
		});

		var city = $("#cboCity").val();
		var sales_date = $("#txtDatePicker").val();
		var prefix = $("#cboCity option:selected").attr("data-id");
		var customer_id = $("#txtCustomerID").val();
		var name = $("#txtName").val();
		var id_no = $("#txtIDNo").val();
		var package = $("#cboPackage").val() + '_' + $("#cboMonths").val() + 'M';
		var mbps = $("#cboPackage option:selected").attr("data-mbps");
		var months = $("#cboMonths").val();
		// var days = $("#cboPackage option:selected").attr("data-days");
		var package_price = parseInt($("#txtPackagePrice").val().replace(/,/g, ''));
		var installation_fee = parseInt($("#txtInstallationFee").val().replace(/,/g, ''));
		var tax_percent = parseInt($("#txtTaxPercent").val().replace(/,/g, ''));
		var normal_discount = parseInt($("#txtNormalDiscount").val().replace(/,/g, ''));
		var member_discount = parseInt($("#txtMemberDiscount").val().replace(/,/g, ''));
		var promotion_discount = parseInt($("#txtPromotionDiscount").val().replace(/,/g, ''));
		var days = $("#txtDays").val();

		if($('input[name=r1]:checked').val()=='Sales'){
			var start_date = "";
			var end_date = "";
		}else{
			var start_date = $("#txtStartDate").val();
			var end_date = "";
		}

		var refund_amount = parseInt($("#txtRefundAmount").val().replace(/,/g, ''));
		var price_change_charges = parseInt($("#txtPriceChangeCharges").val().replace(/,/g, ''));

		var payment_type = $("#cboPaymentType").val();
		var payment = parseInt($("#txtPayment").val().replace(/,/g, ''));

		var installation_address = $("#txtInstallAddress").val();

		var extra_mbps = $("#txtPDExtraBandwidth").val();
		var extra_days = $("#txtPDExtraDays").val();
		var gift = $("#txtPDGift").val();
		var S_R = $('input[name=r1]:checked').val();

		if(id_no==""){
			bootbox.alert("Please fill ID No.");
			return false;
		}else if(name.trim()==""){
			bootbox.alert("Please fill Customer Name.");
			return false;
		}else{

			$.ajax({
				type: "POST",
				url: APP_URL + "api/sales/create.php",
				data: JSON.stringify({ city: city, sales_date: sales_date, prefix: prefix, customer_id: customer_id, name: name, id_no: id_no, package: package, mbps: mbps, months :months, days: days, extra_mbps: extra_mbps, extra_days: extra_days, gift: gift, package_price: package_price, installation_fee: installation_fee, tax_percent: tax_percent, normal_discount: normal_discount, member_discount: member_discount, promotion_discount: promotion_discount, start_date: start_date, end_date: end_date, refund_amount: refund_amount, price_change_charges: price_change_charges, payment_type: payment_type, payment: payment, installation_address: installation_address, S_R: S_R,  details: details }),
				success: function(data){	
					if(data.message=="created"){
						clearAll();
					}else if(data.message=="duplicate"){
						bootbox.alert("Duplicate Card No.");
					}else{
						bootbox.alert("Error on server side.");
					}
				}
			});
		}
	}

	function clearAll(){
		var cc = $("#cboCity").val();
		var nrr = $('input[name=r1]:checked').val();
		var dd = $("#txtDatePicker").val();
		$("#frmEntry")[0].reset();
		$("#txtDatePicker").val(dd);
		$("#datePicker").datepicker("setDate", dd);
		$("#txtStartDate").val(customDate);
		$("#datePicker1").datepicker("setDate", customDate);
		$("#cboCity").val(cc);
		$("input[name=r1][value=" + nrr + "]").prop('checked', true);

		$("#btnRefund").html("Refund");

	}

	function clearDate(){
		var dr = $("#txtDatePicker").val();
		var cc = $("#cboCity").val();
		var nrr = $('input[name=r1]:checked').val();
		$("#frmEntry")[0].reset();
		$("#txtDatePicker").val(dr);
		$("#datePicker").datepicker("setDate", dr);
		$("#txtStartDate").val(dr);
		$("#datePicker1").datepicker("setDate", dr);
		$("#cboCity").val(cc);
		$("input[name=r1][value=" + nrr + "]").prop('checked', true);

		$("#btnRefund").html("Refund");

	}



	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){
		if($(obj).val() == "")$(obj).val(0);
	}

</script>

