<?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';
	?>
	
	<link rel="stylesheet" href="assets/css/jquery-ui.css">
	 
</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>Sales List</h4>
						<h6>Manage your sales</h6>
					</div>
					<div class="page-btn">
						<a href="pos-panel.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>
							<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="GET" enctype="multipart/form-data">
											<div class="row">
												<div class="col-lg-4 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" value="<?php echo isset($_GET['start_date']) ? htmlspecialchars($_GET['start_date']) : ''; ?>" class="form-control">
													</div>
												</div>
												<div class="col-lg-4 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" value="<?php echo isset($_GET['end_date']) ? htmlspecialchars($_GET['end_date']) : ''; ?>" class="form-control">
													</div>
												</div>
												<div class="col-lg-4 col-sm-6 col-12">
													<div class="form-group">
														<button type="submit" name="search" class="btn btn-block btn-outline-success active btn-md text-white" style="margin-top:33px;width:100%;" class="btn btn-filters ms-auto">
														<i class="fa fa-search" aria-hidden="true"></i> Search
														</button>
													</div>
												</div>
												
												<div class="col-lg-4 col-sm-6 col-12" style="margin-top:5px;">
														<button onclick="deleteSelectedRows()" class="btn btn-block btn-outline-danger active btn-md text-white">Delete Selected Rows</button>
												</div>
												<div class="col-lg-4 col-sm-6 col-12" style="margin-top:5px;">
														<span onclick="printelectedRows()" class="btn btn-block btn-outline-danger active btn-md text-white">Print Selected Rows</span>
												</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>Pay Type</th>
										<th>View Items</th>
										<th>Bill Amount</th>
										<th>Paid Amount</th>
										<th>Balance Amount</th>
										<th>Line Discount</th>
										<th>Bill Discount</th>
										<th>Profit(Normal)</th>
										<th>Add Date/Time</th>
									</tr>
								</thead>
								<tbody>
									<?php
									if (isset($_GET['search'])) {
										
										$count=0;
										
										$profit=0;
										$marketprofit=0;
										
										$pro_qty =0;
										$pro_discount=0;
										
										$total_discount_amount=0;
										
										$totalrowbillamount=0;
										$totalrowpaidamount=0;
										$totalrowdueamount=0;
										$totalrowdiscountamount=0;
										$totalrowalldiscountamount=0;
										$totalrowprofitamount=0;
										$totalrowmarketprofitamount=0;
										
										
										$start_date = $_GET['start_date'];
										$end_date = $_GET['end_date'];

									/*	if ($branch_id == '1') {

										$stmt = $DB_con->prepare("SELECT mo.order_id as moorderid,mo.orid,mo.customer,mo.pay_option,mo.amount as moamount,mo.paid_amount,mo.due_amount,mtc.pro_discount,mtc.proid,mtc.discount_type,mo.discount,mo.all_discount,mo.discount_type,mo.status as mostatus,mo.create_at,SUM(mtc.pro_price * mtc.pro_qty) as totalbillptotal,SUM(mp.price * mtc.pro_qty) as totalproducttotal,SUM(mp.market_price * mtc.pro_qty) as totalproductmarkettotal  
FROM mobileorders mo INNER JOIN 
mobiletemporarycart mtc ON mo.order_id=mtc.orderid INNER JOIN
mobileproducts mp ON mtc.proid=mp.prid INNER JOIN
invoice_other_details iod ON mtc.orderid=iod.order_id
WHERE mo.create_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59' GROUP BY mo.order_id ORDER BY mo.create_at DESC");

										} else { */

										$stmt = $DB_con->prepare("SELECT mo.order_id as moorderid,mo.orid,mo.customer,mo.pay_option,mo.amount as moamount,mo.paid_amount,mo.due_amount,mtc.pro_discount,mtc.proid,mtc.discount_type,mtc.pro_discount,mtc.pro_qty,mo.discount,mo.all_discount,mo.discount_type,mo.status as mostatus,mo.create_at,SUM(mtc.pro_price * mtc.pro_qty) as totalbillptotal,SUM(mp.price * mtc.pro_qty) as totalproducttotal,SUM(mp.market_price * mtc.pro_qty) as totalproductmarkettotal  
FROM mobileorders mo INNER JOIN 
mobiletemporarycart mtc ON mo.order_id=mtc.orderid INNER JOIN
mobileproducts mp ON mtc.proid=mp.prid
WHERE mo.branch_id='$branch_id' AND mo.create_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59' GROUP BY mo.order_id ORDER BY mo.create_at DESC");

										//}
										
										$stmt->execute();

										if($stmt->rowCount() > 0)

										{

										while($row=$stmt->fetch(PDO::FETCH_ASSOC))

										{

										extract($row);
										
										if($row['proid']==148){
										
										$profit="0";
										
										$marketprofit="0";

                                        }else{

										//$profit=$row['totalbillptotal']-$row['totalproducttotal']-$row['discount'];
										//$profit=$row['paid_amount']-$row['totalproducttotal'];

										$oooid = $row['moorderid'];
										$orders = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(amount) as amount FROM mobileorders WHERE order_id='$oooid'"));
										$productcost = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(mobileproducts.price * mobiletemporarycart.pro_qty) as cost
														FROM mobiletemporarycart
														JOIN mobileproducts ON mobiletemporarycart.proid = mobileproducts.prid WHERE mobiletemporarycart.orderid='$oooid'"));
										$profit = $orders['amount'] - $productcost['cost'];
										$marketprofit=$row['totalproductmarkettotal']-$row['totalproducttotal']-$row['discount'];
											
										}
										
										$pro_qty = $row["pro_qty"];
										$pro_discount = $row["pro_discount"];
										
										$total_discount_amount=$pro_discount * $pro_qty;

										$totalrowbillamount=$totalrowbillamount+$row['moamount'];
										$totalrowpaidamount=$totalrowpaidamount+$row['paid_amount'];
										$totalrowdueamount=$totalrowdueamount+$row['due_amount'];
										$totalrowdiscountamount=$totalrowdiscountamount+$row['discount'];
										$totalrowalldiscountamount=$totalrowalldiscountamount+$row['all_discount'];
										$totalrowprofitamount=$totalrowprofitamount+$profit;
										$totalrowmarketprofitamount=$totalrowmarketprofitamount+$marketprofit;
										
										$count++;

										?>


											<tr>
												<td>
													<input type="checkbox" class="delete-checkbox" value="<?php echo $row['moorderid']; ?>">
												</td>
												<td>
												<?php echo number_format($count,0); ?>
												</td>
												<td>
													<a href="pos-panel.php?order_id=<?php echo $row['moorderid']; ?>" 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 $row['moorderid']; ?>" 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="salesrecieptnewa4.php?receiptno=<?php echo $row['moorderid']; ?>" 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>
												</td>
												<td>
												<?php echo $row['orid']; ?>
												</td>

												<td>
													<?php
													if($row['moamount']==0){
														echo '<a class="badges bg-secondary text-white">Return</a>';
													}else{
													if ($row['mostatus'] == "2") {
														echo '<a class="badges bg-danger text-white">Rejected</a>';
													} else if ($row['mostatus'] == "0") {
														echo '<a class="badges bg-dark text-white">Pending</a>';
													} else if ($row['mostatus'] == "1") {
														echo '<a class="badges bg-success text-white">Completed</a>';
													} else if ($row['mostatus'] == "3") {
														echo '<a class="badges bg-primary text-white">Barcode</a>';
													}
												}
													?>
												</td>
												
												<td>
													<?php

													if ($row['customer'] == "0") {
														echo '<a class="badges bg-lightgreen text-white">Walk-in Customer</a>';
													} else if ($row['customer'] == "dc") {
														echo '<a class="badges bg-lightgreen text-white">Delivery Customer</a>';
													} else {
														$id = $row['customer'];
														$query = $DB_con->prepare('SELECT cname FROM mobilecustomers WHERE coid=' . $id);
														$query->execute();
														$result = $query->fetch();
														echo $result['cname'];
													}
													?>
												</td>
												<td><a class="badges bg-dark text-white"><?php echo $row['pay_option']; ?></a></td>
												<td class="productimgname">
												<a href="viewsalesitemslist.php?order_id=<?php echo $row['moorderid']; ?>" 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)$row['moamount'], 2); ?>
												</td>
												<td>
												Rs.<?php echo number_format((float)$row['paid_amount'], 2); ?>
												</td>
												<td class="text-red">
												Rs.<?php echo number_format((float)$row['due_amount'], 2); ?>
												</td> 
												<td>
												Rs.<?php echo number_format((float)$row['discount'], 2); ?>
												</td>
												<td class="text-red">
												Rs.<?php echo number_format((float)$row['all_discount'], 2); ?>
												</td>
												<td class="text-red">
												Rs.<?php echo number_format((float)$profit, 2); ?>
												</td> 
												<td class="text-red">
												<?php echo date_format(date_create($row['create_at']), "M d, Y | h:i:s "); ?>
												</td>
											</tr>

										<?php 
										
										}
										
										}
										
										}else{
										$count=0;
										$profit=0;
										$marketprofit=0;
										$pro_qty =0;
										$pro_discount=0;
										$total_discount_amount=0;
										$totalrowbillamount=0;
										$totalrowpaidamount=0;
										$totalrowdueamount=0;
										$totalrowdiscountamount=0;
										$totalrowalldiscountamount=0;
										$totalrowprofitamount=0;
										$totalrowmarketprofitamount=0;
										/*if ($branch_id == '1') {
										$stmt = $DB_con->prepare("SELECT mo.order_id as moorderid,mo.orid,mo.customer,mo.pay_option,mo.amount as moamount,mo.paid_amount,mo.due_amount,mtc.proid,mtc.pro_discount,mtc.discount_type,mo.discount,mo.all_discount,mo.discount_type,mo.status as mostatus,mo.create_at,SUM(mtc.pro_price * mtc.pro_qty) as totalbillptotal,SUM(mp.price * mtc.pro_qty) as totalproducttotal,SUM(mp.market_price * mtc.pro_qty) as totalproductmarkettotal  
FROM mobileorders mo INNER JOIN 
mobiletemporarycart mtc ON mo.order_id=mtc.orderid INNER JOIN
mobileproducts mp ON mtc.proid=mp.prid INNER JOIN
GROUP BY mo.order_id ORDER BY mo.create_at DESC");

										} else { */
											
										$stmt = $DB_con->prepare("SELECT mo.order_id as moorderid,mo.orid,mo.customer,mo.pay_option,mo.amount as moamount,mo.paid_amount,mo.due_amount,mtc.proid,mtc.pro_discount,mtc.discount_type,mtc.pro_discount,mtc.pro_qty,mo.discount,mo.all_discount,mo.discount_type,mo.status as mostatus,mo.create_at,SUM(mtc.pro_price * mtc.pro_qty) as totalbillptotal,SUM(mp.price * mtc.pro_qty) as totalproducttotal,SUM(mp.market_price * mtc.pro_qty) as totalproductmarkettotal 
FROM mobileorders mo INNER JOIN 
mobiletemporarycart mtc ON mo.order_id=mtc.orderid INNER JOIN
mobileproducts mp ON mtc.proid=mp.prid
WHERE mo.branch_id='$branch_id' GROUP BY mo.order_id ORDER BY mo.create_at DESC");

										//}
										
										$stmt->execute();

										if($stmt->rowCount() > 0)

										{

										while($row=$stmt->fetch(PDO::FETCH_ASSOC))

										{

										extract($row);
										
										if($row['proid']==148){
										
										$profit="0";
										
										$marketprofit="0";

                                        }else{

										//$profit=$row['totalbillptotal']-$row['totalproducttotal']-$row['discount'];
										//$profit=$row['paid_amount']-$row['totalproducttotal'];
										$oooid = $row['moorderid'];
										$orders = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(amount) as amount FROM mobileorders WHERE order_id='$oooid'"));
										$productcost = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(mobileproducts.price * mobiletemporarycart.pro_qty) as cost
														FROM mobiletemporarycart
														JOIN mobileproducts ON mobiletemporarycart.proid = mobileproducts.prid WHERE mobiletemporarycart.orderid='$oooid'"));
										$profit = $orders['amount'] - $productcost['cost'];



										$marketprofit=$row['totalproductmarkettotal']-$row['totalproducttotal']-$row['discount'];
											
										}
										
										$pro_qty = $row["pro_qty"];
										$pro_discount = $row["pro_discount"];
										
										$total_discount_amount= $pro_discount * $pro_qty;

										$totalrowbillamount=$totalrowbillamount+$row['moamount'];
										$totalrowpaidamount=$totalrowpaidamount+$row['paid_amount'];
										$totalrowdueamount=$totalrowdueamount+$row['due_amount'];
										$totalrowdiscountamount=$totalrowdiscountamount+$row['discount'];
										$totalrowalldiscountamount=$totalrowalldiscountamount+$row['all_discount'];
										$totalrowprofitamount=$totalrowprofitamount+$profit;
										$totalrowmarketprofitamount=$totalrowmarketprofitamount+$marketprofit;

										$count++;
										?>


											<tr>
												<td>
													<input type="checkbox" class="delete-checkbox" value="<?php echo $row['moorderid']; ?>">
												</td>
												<td>
												<?php echo number_format($count,0); ?>
												</td>
												<td>
													<a href="pos-panel.php?order_id=<?php echo $row['moorderid']; ?>" 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 $row['moorderid']; ?>" 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="salesrecieptnewa4.php?receiptno=<?php echo $row['moorderid']; ?>" 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>
												</td>
												<td>
												<?php echo $row['orid']; ?>
												</td>

												<td>
													<?php
													if($row['moamount']==0){
														echo '<a class="badges bg-secondary text-white">Return</a>';
													}else{
													if ($row['mostatus'] == "2") {
														echo '<a class="badges bg-danger text-white">Rejected</a>';
													} else if ($row['mostatus'] == "0") {
														echo '<a class="badges bg-dark text-white">Pending</a>';
													} else if ($row['mostatus'] == "1") {
														echo '<a class="badges bg-success text-white">Completed</a>';
													} else if ($row['mostatus'] == "3") {
														echo '<a class="badges bg-primary text-white">Barcode</a>';
													}
												}
													?>
												</td>
												
												<td>
													<?php

													if ($row['customer'] == "0") {
														echo '<a class="badges bg-lightgreen text-white">Walk-in Customer</a>';
													} else if ($row['customer'] == "dc") {
														echo '<a class="badges bg-lightgreen text-white">Delivery Customer</a>';
													} else {
														$id = $row['customer'];
														$query = $DB_con->prepare('SELECT cname FROM mobilecustomers WHERE coid=' . $id);
														$query->execute();
														$result = $query->fetch();
														echo $result['cname'];
													}
													?>
												</td>
												<td><a class="badges bg-dark text-white"><?php echo $row['pay_option']; ?></a></td>
												<td class="productimgname">
												<a href="viewsalesitemslist.php?order_id=<?php echo $row['moorderid']; ?>" 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)$row['moamount'], 2); ?>
												</td>
												<td>
												Rs.<?php echo number_format((float)$row['paid_amount'], 2); ?>
												</td>
												<td class="text-red">
												Rs.<?php echo number_format((float)$row['due_amount'], 2); ?>
												</td> 
												<td>
												Rs.<?php echo number_format((float)$row['discount'], 2); ?>
												</td>
												<td class="text-red">
												Rs.<?php echo number_format((float)$row['all_discount'], 2); ?>
												</td>
												<td class="text-red">
												Rs.<?php echo number_format((float)$profit, 2); ?>
												</td>    
												<td class="text-red">
													<?php echo date_format(date_create($row['create_at']), "M d, Y | h:i:s "); ?>
												</td>
											</tr>




									<?php 
									}
									}
									} 
									?>

								</tbody>
								<tfoot style="background-color:#008b0b;color:#ffffff;">
									<tr>
										<th></th>
										<th></th>
										<th></th>
										<th></th>
										<th></th>
										<th></th>
										<th></th>
										<th><strong>All Total</strong></th>
										<th>Rs.<?php echo number_format((float)$totalrowbillamount,2); ?></th>
										<th>Rs.<?php echo number_format((float)$totalrowpaidamount,2); ?></th>
										<th>Rs.<?php echo number_format((float)$totalrowdueamount,2); ?></th>
										<th>Rs.<?php echo number_format((float)$totalrowdiscountamount,2); ?></th>
										<th>Rs.<?php echo number_format((float)$totalrowalldiscountamount,2); ?></th>
										<th>Rs.<?php echo number_format((float)$totalrowprofitamount,2); ?></th>
										<th></th>
										<th></th>
									</tr>
								</tfoot>
							</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);

            }
			
        });
		
    }
	function printelectedRows() {
        var checkboxes = document.querySelectorAll('.delete-checkbox:checked');

        var selectedIds = [];

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

        $.ajax({
            url: 'print_sale_checks.php',		
            type: 'POST',
            data: {selectedIds: selectedIds}, 
            success: function(response) {
               
                var printWindow = window.open('print_sale_checks.php', '_blank');
				printWindow.document.write(response);
				printWindow.document.close();
				printWindow.focus();
				printWindow.print();
            },
            error: function(xhr, status, error) {
                

            }
			
        });
		
    }
</script>

	<!-- end -->

	<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 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" defer></script>

	<script src="assets/js/jquery.slimscroll.min.js" defer></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" defer></script>

	<script src="assets/js/moment.min.js" defer></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" defer></script>
	<script src="assets/js/vfs_fonts.js" defer></script>

	<script src="assets/plugins/sweetalert/sweetalert2.all.min.js" defer></script>
	<script src="assets/plugins/sweetalert/sweetalerts.min.js" defer></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" defer></script>
	<script src="assets/js/dataTables.buttons.min.js"></script>
	<script src="assets/js/jszip.min.js" defer></script>
	<script src="assets/js/buttons.html5.min.js" defer></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>
	// Initialize Select2 plugin with typing search functionality
	$('.select2').select2();
	</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(){
		var table = $('#dtable').DataTable();


		function calculateTotal(columnIndex) {
                var total = 0;
                table.column(columnIndex).data().each(function(value, index) {
                    total += parseFloat(value);
                });
                return total;
        }

		$('#total-dis').text(calculateTotal(7));
		$('#total-amount').text(calculateTotal(8));
		$('#total-bill').text(calculateTotal(9));
		$('#total-profit').text(calculateTotal(10));
		$('#total-profitm').text(calculateTotal(11));



		$("#min-date, #max-date").datepicker({
        	dateFormat: 'yy-mm-dd'
    	});

		$.fn.dataTable.ext.search.push(
        function(settings, data, dataIndex) {
            var min = $('#min-date').datepicker("getDate");
            var max = $('#max-date').datepicker("getDate");
            var date = new Date(data[1]);

            if (
                (min === null && max === null) ||
                (min === null && date <= max) ||
                (min <= date && max === null) ||
                (min <= date && date <= max)
            ) {
                return true;
            }
            return false;
        }
    );
		$('#min-date, #max-date').change(function() {
        	table.draw();
    	});


$("#min-date, #max-date").datepicker({
        	dateFormat: 'yy-mm-dd'
    	});

var table = $('#dtable').DataTable({
        "footerCallback": function (row, data, start, end, display) {
            var api = this.api();

           
            var intVal = function (i) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '')*1 :
                    typeof i === 'number' ?
                        i : 0;
            };

          
            var columns = [7, 8, 9, 10, 11];

            
            columns.forEach(function (columnIndex) {
                // Total over all pages
                var total = api
                    .column(columnIndex)
                    .data()
                    .reduce(function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0);

                
                var pageTotal = api
                    .column(columnIndex, { page: 'current' })
                    .data()
                    .reduce(function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0);

                
                $(api.column(columnIndex).footer()).html(
                    'Rs.' + pageTotal + ' ( Rs.' + total + ' total)'
                );
            });
        }
    });
	
   
    $.fn.dataTable.ext.search.push(
        function(settings, data, dataIndex) {
            var min = $('#min-date').datepicker("getDate");
            var max = $('#max-date').datepicker("getDate");

           
            var dateStr = data[13];
            var dateParts = dateStr.split(' | ')[0].split(' ');
            var timeParts = dateStr.split(' | ')[1].split(':');

            var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            var monthIndex = monthNames.indexOf(dateParts[0]);

            var day = parseInt(dateParts[1].replace(',', ''));
            var year = parseInt(dateParts[2]);
            var hours = parseInt(timeParts[0]);
            var minutes = parseInt(timeParts[1]);
            var seconds = parseInt(timeParts[2]);

            var date = new Date(year, monthIndex, day, hours, minutes, seconds);

            if (
                (min === null && max === null) ||
                (min === null && date <= max) ||
                (min <= date && max === null) ||
                (min <= date && date <= max)
            ) {
                return true;
            }
            return false;
        }
    );

   
    $('#min-date, #max-date').change(function() {
        table.draw();
    });

		
		
		$('#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>