<?php
include 'load.php';

?>

<!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 - Eat More Resturant   | Pos & Invetory System | Dashboard">
	<meta name="keywords" content="Eat More Resturant   | Pos & Invetory System | Dashboard">
	<meta name="author" content="Eat More Resturant   | Pos & Invetory System | Dashboard">
	<meta name="robots" content="noindex, nofollow">

	<title>Card Sales Report | Eat More Resturant   | Pos & Invetory System | Dashboard</title>

	<?php
	require_once 'headercss.php';
	?>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/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>Card Sales Report</h4>
						<h6>Manage your Card sales</h6>
					</div>
				</div>

				<div class="card">
					<div class="card-body">
						<div class="table-top">

						</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-3 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 $_GET['start_date']; ?>" class="form-control">
													</div>
												</div>
												<div class="col-lg-4 col-sm-3 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 $_GET['end_date']; ?>" class="form-control">
													</div>
												</div>
												<div class="col-lg-2 col-sm-3 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%;">
														<i class="fa fa-search" aria-hidden="true"></i> Search
														</button>
													</div>
												</div>

											</div>
										</form>

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

						<div class="table-responsive">
<table class="table" id="betable">
<thead>
									<tr>
										<th>#ID</th>
										<th>Order ID</th>
										<th>Status</th>
										<th>Customer</th>
										<th>Pay Type</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>Profit(Market Price)</th>
										<th>Add Date/Time</th>
									</tr>
								</thead>
								<tbody>
									<?php
									if (isset($_GET['search'])) {
										
										$count=0;
										
										$profit=0;
										$marketprofit=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' AND mo.pay_option='card' 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,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 iod.branch_id='$branch_id' AND mo.create_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59' AND mo.pay_option='card' 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'];
										
										$marketprofit=$row['totalproductmarkettotal']-$row['totalproducttotal']-$row['discount'];
											
										}
										
										$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>
												<?php echo number_format($count,0); ?>
												</td>
												<td>
												<?php echo $row['orid']; ?>
												</td>

												<td>
													<?php
													if ($row['mostatus'] == "2") {
														echo '<a class="badges bg-lightgreen text-white">Rejected</a>';
													} else if ($row['mostatus'] == "0") {
														echo '<a class="badges bg-lightred text-white">Pending</a>';
													} else if ($row['mostatus'] == "1") {
														echo '<a class="badges bg-lightgreen text-white">Completed</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>
													<?php


													if ($row['pay_option'] == "cash") {
														echo '<a class="badges bg-lightgreen text-white">Cash</a>';
													} else if ($row['pay_option'] == "card") {
														echo '<a class="badges bg-lightred text-white">Card</a>';
													} else if ($row['pay_option'] == "banktransfer") {
														echo '<a class="badges bg-lightred text-white">Bank Transfer</a>';
													} else if ($row['pay_option'] == "cheques") {
														echo '<a class="badges bg-lightred text-white">Cheques</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">
												Rs.<?php echo number_format((float)$marketprofit, 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;
										
										$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
invoice_other_details iod ON mtc.orderid=iod.order_id
WHERE mo.pay_option='card' 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,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 iod.branch_id='$branch_id' AND mo.pay_option='card' 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'];
										
										$marketprofit=$row['totalproductmarkettotal']-$row['totalproducttotal']-$row['discount'];
											
										}
										
										$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>
												<?php echo number_format($count,0); ?>
												</td>
												<td>
												<?php echo $row['orid']; ?>
												</td>

												<td>
													<?php
													if ($row['mostatus'] == "2") {
														echo '<a class="badges bg-lightgreen text-white">Rejected</a>';
													} else if ($row['mostatus'] == "0") {
														echo '<a class="badges bg-lightred text-white">Pending</a>';
													} else if ($row['mostatus'] == "1") {
														echo '<a class="badges bg-lightgreen text-white">Completed</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>
													<?php


													if ($row['pay_option'] == "cash") {
														echo '<a class="badges bg-lightgreen text-white">Cash</a>';
													} else if ($row['pay_option'] == "card") {
														echo '<a class="badges bg-lightred text-white">Card</a>';
													} else if ($row['pay_option'] == "banktransfer") {
														echo '<a class="badges bg-lightred text-white">Bank Transfer</a>';
													} else if ($row['pay_option'] == "cheques") {
														echo '<a class="badges bg-lightred text-white">Cheques</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">
												Rs.<?php echo number_format((float)$marketprofit, 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><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>Rs.<?php echo number_format((float)$totalrowmarketprofitamount,2); ?></th>
										<th></th>
										<th></th>
									</tr>
								</tfoot>
							</table>
							<!-- check delete -->
							
							
						</div>
					</div>
				</div>

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

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

	<script>
		$(document).ready(function(){
			$("#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 = [5, 6, 7, 8];

            
            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(
                    '$' + pageTotal + ' ( $' + 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[10];
            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();
    });

	});

	</script>
	
</body>
</html>