<?php
session_start();
include 'load.php';
require_once 'db_connection.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>Stock Report | Payroll | Pos & Invetory System | Dashboard
</title>


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

<body>
	<div id="global-loader">
		<div class="whirly-loader"> </div>
	</div>

	<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>Stock Report List</h4>
						<h6>Manage your Stock Report </h6>
					</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-8 col-sm-8 col-12">
													<div class="form-group">
														<label for="start-date">Product</label>
														<select class="form-control select2" name="productid">
															<option value="" selected>Select Product</option>
															<?php

															$stmt = $DB_con->prepare('SELECT * FROM mobileproducts where status="1" ORDER BY prid');

															$stmt->execute();

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

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

																	extract($row);

																	?>
																	<option value="<?php echo $row['prid']; ?>"><?php echo $row['proname']; ?></option>
																	<?php
																}
															}
															?>
														</select>
													</div>
												</div>
												<div class="col-lg-4 col-sm-4 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>
										</form>

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

						<div class="table-responsive">
							<table class="table" id="betable">
								<thead>
									<tr>
										<th>#ID</th>
										<th>Product</th>
										<th>Opening Qty</th>
										<th>Total Qty</th>
										<th>Sales Qty</th>
										<th>Balance Qty</th>
										<th>Date/Time</th>
									</tr>
								</thead>
								<tbody>
									<?php
									if (isset($_POST['search'])) {
										
										$count=0;
										$totalrowopenstock=0;
										$totalrowcurrentstock=0;
										
										$productid = $_POST['productid'];
										
										$sql = "SELECT * FROM mobiletemporarycart LEFT JOIN mobileproducts ON mobileproducts.prid=mobiletemporarycart.proid LEFT JOIN tbl_stock ON mobileproducts.prid=tbl_stock.prid Where mobileproducts.prid='".$productid . "' AND tbl_stock.branch_id='$branch_id' AND mobileproducts.prid!='148' GROUP BY mobileproducts.prid ORDER BY mobiletemporarycart.tempid DESC";

										$result = $conn->query($sql);
										$rowCount = 0;
										$pamount = 0;
										$total_discount = 0;
										$total_amount = 0;
										$current_qty = 0;
										if ($result->num_rows > 0) {
											while ($row = $result->fetch_assoc()) {
												$rowCount = $rowCount + 1;
												$proid = $row["proid"];
												$proname = $row["proname"];
												$cover = $row["cover"];
												$op_qty = $row["qty"];
												$current_qty = $row["qty"];
												$pro_qty = $row["pro_qty"];
												$total_qty = $current_qty + $pro_qty;
												
												$totalrowopenstock=$totalrowopenstock+$op_qty;
												$totalrowcurrentstock=$totalrowcurrentstock+$pro_qty;	
												
												$count++;
												
												?>
												<tr>
													<td><?php echo number_format($count,0); ?></td>
													<td>
													<?php echo $proname; ?>
													</td>
													<td>
														<?php echo $op_qty; ?>
													</td>
													<td>
														<?php echo $total_qty; ?>
													</td>
													<td>
														<?php echo $pro_qty; ?>
													</td>
													<td>
														<?php echo $current_qty; ?>
													</td>
													<td>
													<?php echo date_format(date_create($row['add_date']), "M d, Y | h:i:s "); ?>
													</td>
												</tr>
												<?php
											}
										}
									} else{
										
										
										$count=0;
										$totalrowopenstock=0;
										$totalrowcurrentstock=0;
										
										$sql = "SELECT * FROM mobiletemporarycart LEFT JOIN mobileproducts ON mobileproducts.prid=mobiletemporarycart.proid LEFT JOIN tbl_stock ON mobileproducts.prid=tbl_stock.prid WHERE  tbl_stock.branch_id='$branch_id' AND mobileproducts.prid!='148' GROUP BY mobileproducts.prid ORDER BY mobiletemporarycart.tempid DESC";

										$result = $conn->query($sql);
										$rowCount = 0;
										$pamount = 0;
										$total_discount = 0;
										$total_amount = 0;
										$current_qty = 0;
										if ($result->num_rows > 0) {
											while ($row = $result->fetch_assoc()) {
												$rowCount = $rowCount + 1;
												$proid = $row["proid"];
												$proname = $row["proname"];
												$cover = $row["cover"];
												$op_qty = $row["qty"];
												$current_qty = $row["qty"];
												$pro_qty = $row["pro_qty"];
												$total_qty = $current_qty + $pro_qty;
												
												$totalrowopenstock=$totalrowopenstock+$op_qty;
												$totalrowcurrentstock=$totalrowcurrentstock+$pro_qty;	

												$count++;
												
												?>
												<tr>
													<td><?php echo number_format($count,0); ?></td>
													<td>
													<?php echo $proname; ?>
													</td>
													<td>
														<?php echo $op_qty; ?>
													</td>
													<td>
														<?php echo $total_qty; ?>
													</td>
													<td>
														<?php echo $pro_qty; ?>
													</td>
													<td>
														<?php echo $current_qty; ?>
													</td>
													<td>
													<?php echo date_format(date_create($row['add_date']), "M d, Y | h:i:s "); ?>
													</td>
												</tr>
												<?php
											}
										}
									}
									?>
								</tbody>
								<tfoot style="background-color:#008b0b;color:#ffffff;">
									<tr>
										<th></th>
										<th><strong>All Total</strong></th>
										<th><?php echo number_format((float)$totalrowopenstock,2); ?></th>
										<th><?php echo number_format((float)$totalrowcurrentstock,2); ?></th>
										<th></th>
										<th></th>
										<th></th>
									</tr>
								</tfoot>
							</table>
						</div>
					</div>
				</div>

			</div>
		</div>
	</div>
	<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(){
			$("#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>