<?php
session_start();
include 'load.php';
$branch_id = $_SESSION['branch_id'];
?>

<!DOCTYPE html>
<html lang="en">

<head>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
	<meta name="description" content="POS - Payroll | Pos & Invetory System | Dashboard">
	<meta name="keywords" content="Payroll | Pos & Invetory System | Dashboard">
	<meta name="author" content="Payroll | Pos & Invetory System | Dashboard">
	<meta name="robots" content="noindex, nofollow">

	<title>Sales List | Payroll | Pos & Invetory System | Dashboard</title>

	<?php
	require_once 'headercss.php';
	?>
</head>

<body>

	<div class="main-wrapper">
		<?php
		require_once 'header.php';
		?>

		<?php
		require_once 'navbar.php';
		?>

		<div class="page-wrapper">
			<div class="content">
				<div class="page-header">
					<div class="page-title">
						<h4>Pending Sales List</h4>
						<h6>Manage your sales</h6>
					</div>
					<div class="page-btn">
						<a href="pos.php" class="btn btn-added"><img src="assets/img/icons/plus.svg" alt="img" class="me-1">Add Sales</a>
					</div>
				</div>

				<div class="card">
					<div class="card-body">
						<div class="table-top">
							<div class="search-set">
								<div class="search-path">
									<a class="btn btn-filter" id="filter_search">
										<img src="assets/img/icons/filter.svg" alt="img">
										<span><img src="assets/img/icons/closes.svg" alt="img"></span>
									</a>
								</div>
								<div class="search-input">
									<a class="btn btn-searchset"><img src="assets/img/icons/search-white.svg" alt="img"></a>
								</div>
							</div>
							<div class="wordset">
							</div>
						</div>

						<div class="card mb-0" id="filter_inputs" style="display:block;">
							<div class="card-body pb-0">
								<div class="row">
									<div class="col-lg-12 col-sm-12">
										<form method="POST" enctype="multipart/form-data">
											<div class="row">
												<div class="col-lg-3 col-sm-6 col-12">
													<div class="form-group">
														<label for="start-date">Start Date:</label>
														<input type="date" id="start-date" name="start_date" class="form-control">
													</div>
												</div>
												<div class="col-lg-3 col-sm-6 col-12">
													<div class="form-group">
														<label for="end-date">End Date:</label>
														<input type="date" id="end-date" name="end_date" class="form-control">
													</div>
												</div>
												<div class="col-lg-1 col-sm-6 col-12">
													<div class="form-group">
														<button type="submit" name="search" style="margin-top:30px;" class="btn btn-filters ms-auto">
															<img src="assets/img/icons/search-whites.svg" alt="img">
														</button>
													</div>
												</div>

												<div class="col-lg-4 col-sm-6 col-12" style="margin-top: 33px;">
														<button onclick="deleteSelectedRows()" class="btn btn-block btn-outline-danger active btn-sm text-white">Delete Selected Rows</button>
												</div>
											</div>
										</form>

									</div>
								</div>
							</div>
						</div>
						<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="selectall">
  <label class="form-check-label" for="flexCheckDefault">
    Select All
  </label>
</div>
						<div class="table-responsive">
							<table class="table" id="betable">
								<thead>
									<tr>
										<th></th>
										<th>#ID</th>
										<th>Action</th>
										<th>Order ID</th>
                                        
										<th>Status</th>
										<th>Customer</th>
										<th>Items</th>
										<th>Total Discount</th>
										<th>Total Amount</th>
										<th>Total Bill</th>
										<th>Total Profit</th>
										<th>Pay Type</th>
										<th>Add Date/Time</th>
									</tr>
								</thead>
								<tbody>
									<?php
									if (isset($_POST['search'])) {
										$start_date = $_POST['start_date'];
										$end_date = $_POST['end_date'];

										if ($branch_id == '0') {
										//	$sql = "SELECT * FROM mobileorders 
											//		INNER JOIN invoice_other_details ON invoice_other_details.order_id = mobileorders.order_id 
											//		WHERE mobileorders.create_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59' 
											//		ORDER BY mobileorders.order_id DESC";
										} else {
											//$sql = "SELECT * FROM mobileorders
											//		INNER JOIN invoice_other_details iod ON iod.order_id = mobileorders.order_id 
											//		WHERE iod.branch_id='$branch_id' AND mobileorders.create_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59' 
											//		ORDER BY mobileorders.order_id DESC";

											$sql = "SELECT * FROM mobileorders
													INNER JOIN invoice_other_details iod ON iod.order_id = mobileorders.order_id 
												WHERE mobileorders.branch_id='$branch_id' AND mobileorders.create_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59' AND mobileorders.status='0'
													ORDER BY mobileorders.order_id DESC";
										}


										$rs = $conn->query($sql);

										$result = mysqli_query($conn, $sql);
										if (!$result) {
											die('Query Error: ' . mysqli_error($conn));
										}

										while ($row = $rs->fetch_array()) {
											$OrderId = $row[0];
											$Orid = $row[1];
											$PayOption = $row[2];
											$Amount = $row[3];
											$PaidAmount = $row[4];
											$DueAmount = $row[5];
											$CardNumber = $row[6];
											$CheqNumber = $row[7];
											$CheqDueDate = $row[8];
											$Customer = $row[9];
											$DeliveryCost = $row[10];
											$Country = $row[11];
											$City = $row[12];
											$UserId = $row[13];
											$CreateAt = $row[14];
											$Status = $row[15];
											$Discount = $row[16];
											/////

											$TempItemSql = "SELECT *  FROM mobiletemporarycart WHERE orderid='$OrderId'";
											$TIrs = $conn->query($TempItemSql);
											$pamount = 0;
											$total_discount = 0;
											$total_amount = 0;
											$todiscountamount = 0;
											while ($TIrow = $TIrs->fetch_array()) {
												$CustomerName = $TIrow[1];
												$pro_price = $TIrow[3];
												$pro_dis = $TIrow[4];
												$pro_qty = $TIrow[5];

												$pamount = ($pro_price * $pro_qty) - $pro_dis;
												$total_discount = $total_discount + $pro_dis;
												$total_amount = $total_amount + $pamount;
												$todiscountamount = $total_amount / 100 * $Discount;
											}
									?>


											<tr>
										
												<td>
													<?php echo $OrderId; ?>
												</td>
												<td>
													<a href="deletesaleslist.php?order_id=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-danger active btn-sm text-white" title="Delete Sales" onClick="JavaScript:return confirm('Are your sure delete this sale?');"><i class="fa fa-trash" data-bs-toggle="tooltip" title="" data-bs-original-title="fa fa-trash" aria-label="fa fa-trash"></i></a>
													<a href="pos-panel.php?order_id=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-primary active btn-sm text-white" title="Edit Sales" onClick="JavaScript:return confirm('Are your sure edit this sale?');"><i class="fa fa-edit" data-bs-toggle="tooltip" title="" data-bs-original-title="fa fa-edit" aria-label="fa fa-edit"></i></a>
													<a href="salesreciept.php?receiptno=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="Bill" aria-label="fa fa-print"></i></a>
													<a href="salesrecieptsinhala.php?receiptno=<?php  echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="Sinhala Bill" aria-label="fa fa-print"></i></a>
													<a href="salesreciepta4.php?receiptno=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="A4 Bill" aria-label="fa fa-print"></i></a>
													<a href="salesrecieptsinhalanew.php?receiptno=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="Sinhala Bill New" aria-label="fa fa-print"></i></a>
												</td>
												<td>
													<?php echo $Orid; ?>
												</td>
                                                
												<td>
													<?php
													if ($Status == "2") {
														echo '<a class="badges bg-lightgreen text-white">Rejected</a>';
													} else if ($Status == "0") {
														echo '<a class="badges bg-lightred text-white">Pending</a>';
													} else if ($Status == "1") {
														echo '<a class="badges bg-lightgreen text-white">Completed</a>';
													}
													?>
												</td>
												<td>
													<?php

													if ($Customer == "0") {
														echo '<a class="badges bg-lightgreen text-white">Walk-in Customer</a>';
													} else if ($Customer == "dc") {
														echo '<a class="badges bg-lightgreen text-white">Delivery Customer</a>';
													} else {
														$id = $Customer;
														$query = $DB_con->prepare('SELECT cname FROM mobilecustomers WHERE coid=' . $id);
														$query->execute();
														$result = $query->fetch();
														echo $result['cname'];
													}
													?>
												</td>
												<td class="productimgname">
													<a href="viewsalesitemslist.php?order_id=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-primary active btn-sm text-white"><i class="fa fa-eye" data-bs-toggle="tooltip" title="" data-bs-original-title="fa fa-eye" aria-label="fa fa-eye"></i> View
														Items</a>
												</td>
												<td>Rs.
													<?php echo number_format((float) $todiscountamount, 2); ?>
												</td>
												<td>Rs.
													<?php echo number_format((float) $PaidAmount, 2); ?>
												</td>
												<td>Rs.
													<?php echo number_format((float) $total_amount, 2); ?>
												</td>
												<td class="text-red">Rs.
													<?php
													$profit = 0;
													$cost_price = 0;
													$TempItemSql = "SELECT *  FROM mobiletemporarycart WHERE orderid='$OrderId'";
													$TIrs = $conn->query($TempItemSql);

													while ($TIrow = $TIrs->fetch_array()) {
														$CustomerName = $TIrow[1];
														$pro_price = $TIrow[3];
														$prid = $TIrow[2];
														$pro_dis = $TIrow[4];
														$pro_qty = $TIrow[5];

														$sqlcart = "SELECT * FROM mobileproducts WHERE prid = '$prid'";
														$cartResult = mysqli_query($conn, $sqlcart);

														while ($res = mysqli_fetch_assoc($cartResult)) {
															$one_product_cost = $pro_qty * $res['price'];
															$cost_price += $one_product_cost;
														}
													}
													$profit = $total_amount - $cost_price;

													echo number_format((float) $profit, 2); ?>
												</td>
												<td>
													<?php


													if ($PayOption == "Cash") {
														echo '<a class="badges bg-lightgreen text-white">Cash</a>';
													} else if ($PayOption == "Card") {
														echo '<a class="badges bg-lightred text-white">Card</a>';
													} else if ($PayOption == "Bank-Transfer") {
														echo '<a class="badges bg-lightred text-white">Bank Transfer</a>';
													} else if ($PayOption == "Cheques") {
														echo '<a class="badges bg-lightred text-white">Cheques</a>';
													} else if ($row['pay_option'] == "Credit") {
														echo '<a class="badges bg-lightgreen text-white">Credit</a>';
													}
													?>
												</td>
												<td class="text-red">
													<?php echo date_format(date_create($CreateAt), "M d, Y | h:i:s "); ?>
												</td>
											</tr>



										<?php }
									} else {


										if ($branch_id == '0') {
											//$sql = "SELECT * FROM mobileorders mo INNER JOIN invoice_other_details iod ON iod.order_id=mo.order_id ORDER BY mo.order_id DESC";
										} else {

										//	$sql = "SELECT * FROM mobileorders mo INNER JOIN invoice_other_details iod ON iod.order_id=mo.order_id WHERE iod.branch_id='$branch_id' ORDER BY mo.order_id DESC";

											$sql = "SELECT * FROM mobileorders mo INNER JOIN invoice_other_details iod ON iod.order_id=mo.order_id WHERE mo.branch_id='$branch_id' AND mo.status='0' ORDER BY mo.order_id DESC";
										}

										$rs = $conn->query($sql);
										while ($row = $rs->fetch_array()) {
											$OrderId = $row[0];
											$Orid = $row[1];
											$PayOption = $row[2];
											$Amount = $row[3];
											$PaidAmount = $row[4];
											$DueAmount = $row[5];
											$CardNumber = $row[6];
											$CheqNumber = $row[7];
											$CheqDueDate = $row[8];
											$Customer = $row[9];
											$DeliveryCost = $row[10];
											$Country = $row[11];
											$City = $row[12];
											$UserId = $row[13];
											$CreateAt = $row[14];
											$Status = $row[15];
											$Discount = $row[16];
											/////

											$TempItemSql = "SELECT *  FROM mobiletemporarycart WHERE orderid='$OrderId'";
											$TIrs = $conn->query($TempItemSql);

											$pamount = 0;
											$total_discount = 0;
											$total_amount = 0;
											$todiscountamount = 0;
											while ($TIrow = $TIrs->fetch_array()) {
												$CustomerName = $TIrow[1];
												$prid = $TIrow[2];
												$pro_price = $TIrow[3];
												$pro_dis = $TIrow[4];
												$pro_qty = $TIrow[5];

												$pamount = ($pro_price * $pro_qty) - $pro_dis;
												$total_discount = $total_discount + $pro_dis;
												$total_amount = $total_amount + $pamount;
												$todiscountamount = $total_amount / 100 * $Discount;
											}
										?>


											<tr>
												<td>
												<input type="checkbox" class="delete-checkbox" value="<?php echo $OrderId; ?>">
												</td>
												<td>
													<?php echo $OrderId; ?>
												</td>
												<td>
													<a href="deletesaleslist.php?order_id=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-danger active btn-sm text-white" title="Delete Sales" onClick="JavaScript:return confirm('Are your sure delete this sale?');"><i class="fa fa-trash" data-bs-toggle="tooltip" title="" data-bs-original-title="fa fa-trash" aria-label="fa fa-trash"></i></a>
													<a href="pos-panel.php?order_id=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-primary active btn-sm text-white" title="Edit Sales" onClick="JavaScript:return confirm('Are your sure edit this sale?');"><i class="fa fa-edit" data-bs-toggle="tooltip" title="" data-bs-original-title="fa fa-edit" aria-label="fa fa-edit"></i></a>
													<a href="salesreciept.php?receiptno=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="Bill" aria-label="fa fa-print"></i></a>
													<a href="salesrecieptsinhala.php?receiptno=<?php  echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="Sinhala Bill" aria-label="fa fa-print"></i></a>
													<a href="salesreciepta4.php?receiptno=<?php  echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="A4 Bill" aria-label="fa fa-print"></i></a>
													<a href="salesrecieptsinhalanew.php?receiptno=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-dark active btn-sm text-white" title="Sales Receipt" onClick="JavaScript:return confirm('Are your sure view sales receipt?');"><i class="fa fa-print" data-bs-toggle="tooltip" title="" data-bs-original-title="Sinhala Bill New" aria-label="fa fa-print"></i></a> 
												</td>
												<td>
													<?php echo $Orid; ?>
												</td>
                                               
												<td>
													<?php
													if ($Status == "2") {
														echo '<a class="badges bg-lightgreen text-white">Rejected</a>';
													} else if ($Status == "0") {
														echo '<a class="badges bg-lightred text-white">Pending</a>';
													} else if ($Status == "1") {
														echo '<a class="badges bg-lightgreen text-white">Completed</a>';
													}
													?>
												</td>
												<td>
													<?php

													if ($Customer == "0") {
														echo '<a class="badges bg-lightgreen text-white">Walk-in Customer</a>';
													} else if ($Customer == "dc") {
														echo '<a class="badges bg-lightgreen text-white">Delivery Customer</a>';
													} else {
														$id = $Customer;
														$query = $DB_con->prepare('SELECT cname FROM mobilecustomers WHERE coid=' . $id);
														$query->execute();
														$result = $query->fetch();
														echo $result['cname'];
													}
													?>
												</td>
												<td class="productimgname">
													<a href="viewsalesitemslist.php?order_id=<?php echo $OrderId; ?>" class="btn btn-block btn-outline-primary active btn-sm text-white"><i class="fa fa-eye" data-bs-toggle="tooltip" title="" data-bs-original-title="fa fa-eye" aria-label="fa fa-eye"></i> View
														Items</a>
												</td>
												<td>Rs.
													<?php echo number_format((float) $todiscountamount, 2); ?>
												</td>
												<td>Rs.
													<?php echo number_format((float) $PaidAmount, 2); ?>
												</td>
												<td>Rs.
													<?php echo number_format((float) $total_amount, 2); ?>
												</td>
												<td class="text-red">Rs.
													<?php
													$profit = 0;
													$cost_price = 0;
													$TempItemSql = "SELECT *  FROM mobiletemporarycart WHERE orderid='$OrderId'";
													$TIrs = $conn->query($TempItemSql);

													while ($TIrow = $TIrs->fetch_array()) {
														$CustomerName = $TIrow[1];
														$pro_price = $TIrow[3];
														$prid = $TIrow[2];
														$pro_dis = $TIrow[4];
														$pro_qty = $TIrow[5];

														$sqlcart = "SELECT * FROM mobileproducts WHERE prid = '$prid'";
														$cartResult = mysqli_query($conn, $sqlcart);

														while ($res = mysqli_fetch_assoc($cartResult)) {
															$one_product_cost = $pro_qty * $res['price'];
															$cost_price += $one_product_cost;
														}
													}
													$profit = $total_amount - $cost_price;

													echo number_format((float) $profit, 2); ?>
												</td>
												<td>
													<?php
													if ($PayOption == "Cash") {
														echo '<a class="badges bg-lightgreen text-white">Cash</a>';
													} else if ($PayOption == "Card") {
														echo '<a class="badges bg-lightred text-white">Card</a>';
													}
													?>
												</td>
												<td class="text-red">
													<?php echo date_format(date_create($CreateAt), "M d, Y | h:i:s "); ?>
												</td>
											</tr>


									<?php }
									} ?>

								</tbody>
							</table>
							<!-- check delete -->

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

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


<!-- check delete starts -->
<script>
	
    function deleteSelectedRows() {
        var checkboxes = document.querySelectorAll('.delete-checkbox:checked');

        var selectedIds = [];

        checkboxes.forEach(function(checkbox) {
            selectedIds.push(checkbox.value);
        });

        $.ajax({
            url: 'delete_sale_checks.php',
            type: 'POST',
            data: {selectedIds: selectedIds}, 
            success: function(response) {
                console.log('Rows deleted successfully');
                toastr.success('Rows deleted successfully');
                location.reload(); 
            },
            error: function(xhr, status, error) {
                console.error('Error deleting rows: ', error);
                toastr.error('Error deleting rows: ' + error);

            }
			
        });
		
    }
	
</script>

<script>
		function printDiv(printableArea) {

			var printContents = document.getElementById(printableArea).innerHTML;
			var originalContents = document.body.innerHTML;

			document.body.innerHTML = printContents;

			window.print();

			document.body.innerHTML = originalContents;

		}
	</script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js"></script>

	<script>
	// Initialize Select2 plugin with typing search functionality
	$('.select2').select2();
	</script>
	
	<script data-cfasync="false" src="../../cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script>
							
	<script src="assets/js/jquery-3.6.0.min.js"></script>

	<script src="assets/js/feather.min.js"></script>

	<script src="assets/js/jquery.slimscroll.min.js"></script>

	<script src="assets/js/jquery.dataTables.min.js"></script>
	<script src="assets/js/buttons.dataTables.js"></script>
	<script src="assets/js/dataTables.bootstrap4.min.js"></script>

	<script src="assets/js/bootstrap.bundle.min.js"></script>

	<script src="assets/js/moment.min.js"></script>
	<script src="assets/js/bootstrap-datetimepicker.min.js"></script>
	<script src="assets/js/pdfmake.min.js"></script>
	<script src="assets/plugins/select2/js/select2.min.js"></script>
	<script src="assets/js/vfs_fonts.js"></script>

	<script src="assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
	<script src="assets/plugins/sweetalert/sweetalerts.min.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
	<script src="assets/js/dataTables.buttons.min.js"></script>
	<script src="assets/js/jszip.min.js"></script>
	<script src="assets/js/buttons.html5.min.js"></script>
	<script src="assets/js/script.js"></script>
	
	<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

	<script>
		

		$(document).ready( function() {
			$('#betable').DataTable({
        dom: 'Bfrtip', 
        buttons: [
            'copy', 
            'csv',  
            {
                extend: 'excelHtml5', 
                customize: function(xlsx) {
                    var sheet = xlsx.xl.worksheets['sheet1.xml']; 
                    $('row c[r^="C"]', sheet).attr('s', '2'); 
                }
            },
            'pdf',  
            'print' 
        ]
    });
	} );
	</script>
	
	<style>
	#betable_filter{
		margin-bottom: 20px;
	}
	</style>


<script>
	$(document).ready(function(){
		$('#selectall').click(function() {
			var id = $(this).attr('id');

			if($(this).is(':checked')){
				var check = 1;
				$('input[type="checkbox"]').prop('checked', true);
			}else{
				var check = 0;
				$('input[type="checkbox"]').prop('checked', false);
			}


			/*$.ajax({
					type: "POST",
					data: {check:check,id:id},
					url: "checkbox_select.php",
					success: function(data){
							
					}
				});*/

				

		});

	});
</script>

</body>

</html>