<?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">
					<h1>Item Sales - Report</h1>
				</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">Search</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">
							<div class="card-body">
								<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;">Date From&nbsp;<input id="chkDateFrom" type="checkbox" checked >:</label>
											<div class="col-md-8">  
												<div class="input-group">
													<div class="input-group-prepend">
														<span class="input-group-text" style="width: 40px;">
															<i class="far fa-calendar-alt"></i>
														</span>
													</div>
													<input type="text" class="form-control" id="txtDatePicker1" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
												</div>
											</div>
										</div>
									</div>
									<div class="col-md-4">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Store:
											</label>
											<div class="col-md-8">
												<select type="text" class="form-control" id="cboCity" >
												</select>
											</div>
										</div>
                                    		</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 type="text" class="form-control" id="txtName">
						                		</div>
						                	</div>
						                </div>
									<div class="col-md-4">
										<div class="form-group row">
											<label class="col-md-4 col-form-label" style="text-align: right;">Date To: </label>
											<div class="col-md-8">  
												<div class="input-group">
													<div class="input-group-prepend">
														<span class="input-group-text" style="width: 40px;">
															<i class="far fa-calendar-alt"></i>
														</span>
													</div>
													<input type="text" class="form-control" id="txtDatePicker2" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
												</div>
											</div>
										</div>
									</div>
									<div class="col-md-4">
					                	<div class="form-group row">
					                		<label class="col-md-4 col-form-label" style="text-align: right;">Voucher No.: </label>
					                		<div class="col-md-8">
					                			<input type="text" class="form-control" id="txtVoucherNo">
					                		</div>
					                	</div>
					                </div>
					                
					                
					                <div class="col-md-4">
					                	<div class="form-group row">
					                		<div class="col-md-4"></div>
					                		<div class="col-md-4">
					                			<button type="button" class="btn btn-primary btn-block" onclick="search()">Search</button>
					                		</div>
					                		<div class="col-md-4">
					                			<button type="button" id="btnExport" value=" Export Table data into Excel " datafrom="myTable" class="btn btn-success btn-block exportToExcel">Export Data</button> 
					                		</div>
					                	</div>
					                </div>
					            </div>
					        </div>
					    </form>
					</div>
				</div>
			</div>
			<div class="card card-outline card-primary">
				<div class="card-header">
					<h3 class="card-title">Sales 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-bordered" id="myTable">
						<thead>                  
							<tr>
								<th style="width: 3%">#</th>
								<th style="width: 10%">Date</th>
								<th style="width: 10%">Voucher No.</th>
								<th style="width: 10%">Store</th>
								<th>Name</th>
								<th style="width: 10%">Total Amount</th>
								<th style="width: 10%">Discount</th>
                                <th style="width: 10%">Payment</th>
								<th style="width: 10%">Balance</th>
								<th style="width: 13%">Action</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>

				<center>
					<div class="modal fade" id="myModalDetail">
						<div class="modal-dialog" style="max-width: 100% !important;">
							<div class="modal-content" style="width: 85%; top: 30px;">
								<div class="modal-header" style="padding-top:10px; padding-bottom: 10px;">
									<h4 class="modal-title" style="font-size:14px; font-weight:bold;">Voucher No. <span id="mtxtDealerSalesInvoiceNo"></span></h4>
									<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="font-size: 20px;">
										<span aria-hidden="true">&times;</span>
									</button>
								</div>
								<section class="content">
									<div class="container-fluid">
										<div class="row" style="margin-top: 10px;margin-bottom: 10px;">
											<div class="col-md-8">
												<div class="card-body p-0" style="height:390px; overflow-y: auto;background-color: #e6e7e8 !important;">
													<table class="table table-striped table-sm table-responsive" id="myTableModal" style="font-size:12px !important">
														<thead>                  
															<tr>
																<th style="width: 3%;">#</th>
																<th style="width: 15%;">Item Code </th>
																<th>Item Name </th>
																<th style="width: 12%;">Quantity  </th>
																<th style="width: 12%;">Price</th>
																<th style="width: 12%;">Amount</th>
															</tr>
														</thead>
														<tbody>
														</tbody>
													</table>	
												</div>
											</div>
											<div class="col-md-4">
												<div class="form-group row">
													<label class="col-md-6 col-form-label" style="text-align: right;">Date 
													</label>
													<div class="col-md-6">
														<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="txtDatePickerM" value="2020-02-04" aria-label="Date Picker" placeholder="Select a date">
														</div>
													</div>
												</div>
												<div class="form-group row">
													<label class="col-md-6 col-form-label"  style="text-align: right;">Store </label>
													<div class="col-md-6">
														<input type="text" class="form-control" id="txtStoreM" disabled>
													</div>
												</div>
												<div class="form-group row">
													<label class="col-md-6 col-form-label" style="text-align: right;">Voucher No. </label>
													<div class="col-md-6">
														<input type="text" class="form-control" id="txtVoucherNoM" disabled>
													</div>
												</div>
												<div class="form-group row">
													<label class="col-md-6 col-form-label" style="text-align: right;">Name</label>
													<div class="col-md-6">
														<input type="text" class="form-control" id="txtNameM" disabled>
													</div>
												</div>
												<div class="form-group row">
													<label class="col-md-6 col-form-label" style="text-align: right;">Total Amount 
													</label>
													<div class="col-md-6">
														<input type="text" class="form-control" id="txtTotalAmountM" value="0" style="text-align:right;" disabled>
													</div>
												</div>	
												<div class="form-group row">
													<label class="col-md-6 col-form-label" style="text-align: right;">Discount
													</label>
													<div class="col-md-6">
														<input type="text" disabled class="form-control" id="txtTotalDiscountM" value="0" style="text-align:right;" disabled>
													</div>
												</div>
												<div class="form-group row">
													<label class="col-md-6 col-form-label" style="text-align: right;">Payment 
													</label>
													<div class="col-md-6">
														<input type="text" class="form-control" id="txtPaymentM" value="0" style="text-align:right;" disabled>
													</div>
												</div>
											</div>
										</div>
									</div>
								</section>	
							</div>
						</div>
					</div>
				</center>


		</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 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>");	
		}
	});

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

	function getAllCity(){
		$("#cboCity").find("option").remove();
		$("#cboCity").append("<option value= '' data-id = ''>[All]</option>");
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				$("#cboCity").append("<option value= '" + v.name + "'>" + v.name + "</option>");			
			});	
			// $("#cboCity").val(C);	
			// getStockList();
		});

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

	function search(){
		$("#loading").css("display","block");
		var df =($("#chkDateFrom").prop("checked"))?$("#txtDatePicker1").val():"";
		var dt =($("#chkDateFrom").prop("checked"))?$("#txtDatePicker2").val():"";
		var voucher_no = $("#txtVoucherNo").val();
		var city = $("#cboCity").val();
		var name = $("#txtName").val();
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			type: "POST",
			url: APP_URL + "api/item_sales/search.php",
			data: JSON.stringify({ df: df, dt:dt, voucher_no:voucher_no, city:city, name:name }),
			error: function(data) {
				$("#loading").css("display","none");
			}
		}).done(function(data) {
           if(data.records){$("#total_records").text(" - " + data.records.length + " records");}else{$("#total_records").text(0 + " record(s) found.");}
           $("#loading").css("display","none");
           $.each(data.records, function(i, v) {
           	console.log(v);
           	$("#myTable").find("tbody")
           	.append($('<tr>')
           		.append("<td>" + (i+1) + "</td>")
           		.append("<td>" + v.sales_date + "</td>")
           		.append("<td>" + v.voucher_no + "</td>")
           		.append("<td>" + v.city + "</td>")
           		.append("<td>" + v.name + "</td>")
            	.append("<td style='text-align:right;'>" + v.total_amount + "</td>")
            	.append("<td style='text-align:right;'>" + v.discount + "</td>")
            	.append("<td style='text-align:right;'>" + v.payment + "</td>")
           		.append("<td style='text-align:right;'>" + v.balance + "</td>")
                	.append("<td style='width: 70px'><span type='button' class='btn btn-success btn-sm' onclick='gotoSalesView(\"" + v.voucher_no + "\",this)' style='padding: 4px 10px;font-size: 11px; min-width: 30px;'>Detail</span> <span type='button' class='btn btn-info btn-sm' onclick='print(\"" + v.voucher_no + "\", this)' style='padding: 4px 10px; font-size: 11px; min-width: 30px'>Print</span> <span type='button' class='btn btn-danger btn-sm' onclick='del(\"" + v.voucher_no + "\",this)' style='padding: 4px 10px; font-size: 11px; min-width: 30px'>Delete</span></td>")
           		)
           });

		   $("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;">')
			.append("<td colspan='5' style='text-align:right;'>Net Amount:</td>")
			.append("<td style='text-align:right;'>" + ((data.total_amount_T)?data.total_amount_T:0) + "</td>")
			.append("<td style='text-align:right;'>" + ((data.discount_T)?data.discount_T:0) + "</td>")
			.append("<td style='text-align:right;'>" + ((data.payment_T)?data.payment_T:0) + "</td>")
			.append("<td style='text-align:right;'>" + ((data.balance_T)?data.balance_T:0) + "</td>")
  			);  

       });
    }
    
	// <span type='button' class='btn btn-info btn-sm' onclick='pay(\"" + v.voucher_no + "\", this)' style='padding: 4px 10px; font-size: 11px; min-width: 30px'>Payment</span> 

    function gotoSalesView(sid,obj){
		// window.open(APP_URL + "entry/item_sales.php?sid=" + sid  , "_blank");
		// document.location = APP_URL + "expense/purchase.php?pid=" + id  , "_blank";

		$("#myModalDetail").modal('show');	

		clearFormModal();
		$("#mtxtDealerSalesInvoiceNo").text(" - " + sid);
		getOneSales(sid);

	}

	function clearFormModal(){
		$("#txtDatePickerM").val(customDate);
		$("#txtVoucherNoM").val("");
		$("#txtStoreM").val("");
		$("#txtNameM").val("");
		$("#myTableModal tbody tr").remove();
		$("#txtTotalAmountM").val(0);
		$("#txtDiscountM").val(0);
		$("#txtPaymentM").val(0);
	}

	function getOneSales(sid){
		$("#myTableModal").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/item_sales/get_one_sales.php",
			type: "POST",
			data: JSON.stringify({ voucher_no: sid  })
		}).done(function(data) {	
			$("#txtDatePickerM").val(data.sales_date);
			$("#txtNameM").val(data.name);
			$("#txtVoucherNoM").val(data.voucher_no);
			$("#txtStoreM").val(data.store);
			// getAllCustomer(data.customer_id,data.sales_no);
			
			$.each(data.s_details, function(i, v) {
				$("#myTableModal").find("tbody")
		        .append($('<tr>')
					.append("<td style='width: 10px'>" + ($("#myTableModal tbody tr").length +1) + "</td>")
					.append("<td>" + v.item_code + "</td>")
					.append("<td>" + v.item_name + "</td>")
					.append("<td style='text-align:right; '>" + v.quantity + "</td>")
					.append("<td style='text-align:right; '>" + parseInt(v.price).toLocaleString() + "</td>")
					.append("<td style='text-align:right; '>" + parseInt(v.quantity*v.price).toLocaleString() + "</td>")
					// .append("<td style='width: 70px'><button type='button' class='btn btn-danger btn-sm'  style='padding: 0px 19px;font-size: 14px;' onclick='$(this).parent().parent().remove();calculate();'>×</button></td>")
				)
	        });
			$("#txtTotalAmountM").val(data.total_amount);
			$("#txtDiscountM").val(data.discount);
			$("#txtPaymentM").val(data.payment);
			// $("#txtBalance").text(0);
			// window.print();
		});
	}

	function print(vid,obj){
		window.open(APP_URL + "print/item_sales_print.php?vid=" + vid  , "_blank");
		// document.location = APP_URL + "expense/purchase.php?pid=" + id  , "_blank";
	}

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