<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>
<div class="content-wrapper" style="min-height: 1203.6px;">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<div class="container-fluid">
			<div class="row mb-2">
				<div class="col-md-6">
					<h3>Promotion - 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="card-body" style="min-height: 490px;">
							<div class="row">
								<div class="col-md-4">
									<div class="form-group row">
                                        <label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
                                        <div class="col-md-8">
                                            <select type="text" class="form-control" id="cboCity">
                                            	<option value=""></option>
                                            </select>
                                        </div>
                                    </div>
								</div>
								<div class="col-md-2">
									<div class="form-group row">
                                        <label class="col-md-4 col-form-label" style="text-align: right;">Months:</label>
                                        <div class="col-md-8">
                                            <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>
                                    </div>
								</div>
								<div class="col-md-7" style="border-right: 1px solid #dee2e6;">
									<div class="card card-outline card-default">
										<div class="card-header">
											<h3 class="card-title">List <span id="total_records" style="font-weight:bold;"> </span></h3>
										</div>
										<div class="card-body p-0" style="max-height: 450px; overflow-y: auto;">
		                                    <table class="table table-bordered" id="myTable">
		                                        <thead>                  
		                                            <tr style="background-color: #f0f0f0;">
		                                               <th style="width: 3%">#</th>
														<th>City</th>
														<th>Internet Plan</th>
														<th style="text-align: center;display:none;">Mbps</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>
								<div class="col-md-5">
									<div class="form-group row">
										<label class="col-md-4 col-form-label" style="text-align: right;">Promotion Name: </label>
										<div class="col-md-8">
											<input type="text" class="form-control" id="txtPromotionName">
										</div>
									</div>
									<div class="form-group row">
										<label class="col-md-4 col-form-label" style="text-align: right;">Period From/To: </label>
										<div class="col-md-4" style="padding-bottom: 9px;">  
											<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 class="col-md-4">  
											<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">
										<label class="col-md-4 col-form-label" style="text-align: right;">Package Discount(%): </label>
										<div class="col-md-8">
											<input type="text" class="form-control" onfocus="this.select();" onkeypress="return isNumber(event)" onkeyup="btozero(this);" id="txtPackagePrice" value="0" style="text-align:right;">
										</div>
									</div>
									<div class="form-group row">
										<label class="col-md-4 col-form-label" style="text-align: right;"> Fee Discount(%): </label>
										<div class="col-md-8">
											<input type="text" class="form-control" onfocus="this.select();" onkeypress="return isNumber(event)" onkeyup="btozero(this);" id="txtInstallationFee" value="0" style="text-align:right;">
										</div>
									</div>
									<div class="form-group row">
										<label class="col-md-4 col-form-label" style="text-align: right;">Extra Mbps: </label>
										<div class="col-md-3">
											<input type="number" class="form-control" onfocus="this.select();" onkeypress="return isNumber(event)" onkeyup="btozero(this);" id="txtBandwidth" value="0" style="text-align:right;">
										</div>
										<label class="col-md-2 col-form-label" style="text-align: right;">Extra Days: </label>
										<div class="col-md-3">
											<input type="number" class="form-control" onfocus="this.select();" onkeypress="return isNumber(event)" onkeyup="btozero(this);" id="txtExtraDays" value="0" style="text-align:right;">
										</div>
									</div>
									<div class="form-group row">
										<label class="col-md-4 col-form-label" style="text-align: right;">Gift: </label>
										<div class="col-md-6">
											<input type="text" class="form-control" id="txtGift">
										</div>
										<div class="col-md-2">
											<button type="button" class="btn btn-primary btn-block" onclick="addGift();">Add</button>
										</div>
									</div>
									<div class="form-group row">
										<label class="col-md-4 col-form-label" style="text-align: right;"></label>
										<div class="col-md-8">
											<ul class="list-group" style="height:90px; overflow-y: auto;background-color:#ced2d2;margin-bottom:0px" id="giftList"></ul>
										</div>
									</div>
									<div class="form-group row">
										<label class="col-md-8 col-form-label" style="text-align: right;"></label>
										<div class="col-md-4">
											<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 card-primary">
				<div class="card-header">
					<h3 class="card-title">Promotion List<span id="total_promotions" 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-bordered" id="myTable2">
						<thead>                  
							<tr>
								<th style="width: 3%">#</th>
								<th>City </th>
								<th>Internet Plan </th>
								<th>Name</th>
								<th>Period From</th>
								<th>Period To</th>
								<th>Extra Mbps</th>
								<th>Monthly Price Discount(%)</th>
								<th>Fee Discount(%)</th>
								<th>Extra Days</th>
								<th>Gift</th>
								<th>Delete</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script>
	var C = '<?php echo isset($_SESSION['city'])?$_SESSION['city']:""?>';
	var d = new Date();
	var mm = (d.getMonth("MM")+1);
	var dd = d.getDate();
	var yyy = d.getFullYear();
	var customDate = d.getFullYear() + "-" + ((mm<10)?"0" + mm:mm) + "-" +  ((dd<10)?"0" + dd:dd);


	$(function() {
		$("body").addClass("sidebar-collapse");
		$('#txtDatePicker1, #txtDatePicker2').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>");	
		}
	});

	$("#chkSelectAll").click(function() {
	    if ($(this).is(':checked')) {
	        $('input:checkbox').prop('checked', true);
	    } else {
	        $('input:checkbox').prop('checked', false);
	    }
	});

	$("#cboCity").change(function(){
		getPackageByCity();
		getPromotionByCity();
	});

	function addGift(){
		if ($('#txtGift').val()!=""){
			$('#giftList').append("<li class='list-group-item' data-id='" + $("#txtGift").val() + "'><span style='display: inline-block;width: 90%;'>"+$('#txtGift').val()+"</span><button type='button' class='btn btn-sm btn-danger pull-right' onclick='delGift(this)' style='margin-top:-5px;z-index: 2;font-size: 17px;width: 10%;padding: 0px 0px;'>&times;</button></li>");
			$('#txtGift option[value="' + $('#txtGift').val() + '"]').css("display", "none");
			$("#txtGift").val("");
		}
	};	

	function delGift(obj){
		var gift_id=$(obj).parent().attr('data-id');
		$('#txtGift option[value="' + gift_id + '"]').css("display", "block");
		$(obj).parent().remove();
	}

	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 getPackageByCity(){
		var city = $("#cboCity option:selected").val();
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/package/get_all_packages.php",
			type: "POST",
			data: JSON.stringify({ city: city })
		}).done(function(data){
			if(data.records){$("#total_records").text(" - " + data.records.length + " records");}else{$("#total_records").text(0 + " record");}
           	$("#loading").css("display","none");
			$.each(data.records, function(i, v) {
				console.log(v);
		       $("#myTable").find("tbody")
				.append($('<tr>')
					.append("<td style='width: 10px'>" + (i+1) + "</td>")
					.append("<td>" + city + "</td>")
					.append("<td>" + v.package + "</td>")
					.append("<td style='text-align:right;display:none;'>" + v.mbps + "</td>")
					.append("<td style='text-align: center;'><div class='icheck-success d-inline'><input type='checkbox' id='" + v.id + "'><label for='" + v.id + "'></label></div></td>")
				)
			});
		});
	}

	function validateAndSave(){
		$("#loading").css("display", "block");
		var details = [];
		$("#myTable tbody tr td input[type='checkbox']").each(function (){
			var ischecked = $(this).is(":checked");
			if(ischecked){
				var detail = {
					"package" : $(this).parent().parent().parent().find("td").eq(2).text()
				}
				details.push(detail);
			}
		});

		var gift = "";
		$("#giftList li" ).each(function(index) {
			gift += $(this).find("span").eq(0).text() + "|";
		});

		var promotion_list = {
			"name": $("#txtPromotionName").val(),
			"city": $("#cboCity").val(),
			"months": $("#cboMonths").val(),
			"period_from": $("#txtDatePicker1").val(),
			"period_to": $("#txtDatePicker2").val(),
			"bandwidth": $("#txtBandwidth").val(),
			"package_price": $("#txtPackagePrice").val(),
			"installation_fees": $("#txtInstallationFee").val(),
			"extra_days": $("#txtExtraDays").val(),
			"gift": gift,
			"details": details
		}

		if($("#cboCity").val()==""){
			bootbox.alert("Please fill the city.");
			$("#loading").css("display", "none");
			return false;
		}else if(details.length==0){
			bootbox.alert("Please check package list.");
			$("#loading").css("display", "none");
			return false;
		}else if($("#txtPromotionName").val()==""){
			bootbox.alert("Please fill the promotion name.");
			$("#loading").css("display", "none");
			return false;
		}else{
			$("#loading").css("display", "none");
			$.ajax({
				url: APP_URL + "api/promotion/create.php",
				type: "POST",
				data: JSON.stringify(promotion_list)
			}).done(function(data) {
				if(data.message=="created"){
					bootbox.alert("Successfully.");
					$("#cboCity").val("");
					$("#txtPromotionName").val("");
					$("#txtDatePicker1").val(customDate);
					$("#txtDatePicker2").val(customDate);
					$("#txtPackagePrice").val(0);
					$("#txtInstallationFee").val(0);
					$("#txtBandwidth").val(0);
					$("#txtExtraDays").val(0);
					$("#txtGift").val("");
					$("#giftList").text("");
					if(C=='Main Office'){
						getAllCity();
					}else{
						$("#cboCity").append("<option value= '" + C + "'  >" + C + "</option>");	
					}
					 $("#chkSelectAll").prop('checked', false);

					if ($("#chkSelectAll").is(':checked')) {
					    $('input:checkbox').prop('checked', true);
					} else {
					    $('input:checkbox').prop('checked', false);
					}
				}else if(data.message=="duplicate"){
					bootbox.alert("Not allow duplicate.");
				}else{
					bootbox.alert("Error on server side.");
				}
			});
		}
	}

	function getPromotionByCity(){
		var city = $("#cboCity option:selected").val();
		$("#myTable2").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/promotion/get_promotion_by_city.php",
			type: "POST",
			data: JSON.stringify({ city: city })
		}).done(function(data){
			if(data.records){$("#total_promotions").text(" - " + data.records.length + " records");}else{$("#total_promotions").text(0 + " record");}
           	$("#loading").css("display","none");
			$.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.city + "</td>")
					.append("<td>" + v.package + "</td>")
					.append("<td>" + v.name + "</td>")
					.append("<td>" + v.period_from + "</td>")
					.append("<td>" + v.period_to + "</td>")
					.append("<td style='text-align:right;'>" + v.bandwidth + "</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.extra_days + "</td>")
					.append("<td>" + v.gift + "</td>")
					.append("<td  style='text-align:right;" + ((v.is_delete)?"display:block;":"display:none;") + "' ><span class='btn btn-danger btn-sm' style='padding: 0px 8px; min-width: 20px;' onclick='del(\"" + v.id + "\",this)' title='Delete'></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/promotion/delete.php",
					data: JSON.stringify({ id: id }),
					success: function(data){
						if(data=="deleted"){
    						$(obj).parent().parent().remove();
    						getPromotionByCity();
    					}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){
		if($(obj).val() == "") $(obj).val(0);
	}	
</script>
