<?php 

require_once("config/configDB.php"); 
require "userPermission.php";
//require_once("config/constant.php");
error_reporting(0);
$sql_supplier = mysqli_query($conn,"SELECT sh.customer_id,cm.cname FROM saleheader as sh  join customer_master as cm on cm.id=sh.customer_id WHERE cm.isdelete='1' GROUP BY sh.customer_id ");

$row_supplier = '';



$fromdate=$_POST['fromDate'];
$todate=$_POST['toDate'];
$customerName=$_POST['customerName'];


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>Stock Report</title>
    <?php require 'header.php' ?>
    <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">

<script >
var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()

</script>
</head>
<body>
    <?php require 'menu.php' ?>


    <div class="container text-center" id="saleStock">
  
  <form class="form-inline" action="customer_statement.php" method="post">
    
    <div class="form-group">
      <label for="email">From Date:</label>
      <input type="date" class="form-control" id="fromDate" name="fromDate" autocomplete="off">
    </div>
    <div class="form-group">
      <label for="pwd">To Date</label>
      <input type="date" class="form-control" id="toDate" name="toDate" autocomplete="off">
    </div>

      <div class="form-group">
      <label for="pwd">Please Select the Customer </label>
      <select class="form-control  supplierStock" name="customerName">
        <option value=""> Select the Customer </option>
        <?php
        while($row = mysqli_fetch_array($sql_supplier)){
        ?>
        <option value="<?php echo $row['customer_id'] ?>" > <?php echo $row['cname']; ?> </option>
        <?php
        }
        ?>
        </select>
    </div>
   
    
 
  
</div>

<div class="container " align="center">
    
    

    <button type="submit" class="btn btn-primary btn-md datewise-submit-sale">Submit</button>&nbsp;
    
   <button type="button" class="btn btn-primary" onClick="tableToExcel('a', 'W3C Example Table')">Download</button> 


    </form>
</div>

   

<br>

<div class="container col-sm-12">
<div id="a">
<table id="salestockDashboard" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
        <thead>
            <tr>
            
            <th>S.No</th>
            <th>Date</th>
            <th>Invoice.No</th>
           <!-- <th>Delivery Address</th>
            <th>Product</th>
            <th>Qty</th>-->
            <th>Payment.No</th>
                <th>Customer Name</th>
                
                <th>Category</th>
                <th>Mode</th>
                 <th>Discount</th>
                <th>Amount</th>
               
                 
               
                <!-- <th>Action</th> -->
            </tr>
        </thead>
        <?php
		$msql=mysqli_query($conn,"select sum(tamount) as salesamount from saleheader where sale_date<'".$fromdate."' and customer_id='".$customerName."' and status=''");
		
		
        
		while($rw=mysqli_fetch_array($msql))
		{
			
		$samount=$rw['salesamount'];	
		}
			
		
        $msql1=mysqli_query($conn,"select sum(received_amount) as collamount,sum(discount) as discountamount from customer_payment_header where collectiondate<'".$fromdate."' and customerID='".$customerName."' and status=''");
		
        
		while($rw1=mysqli_fetch_array($msql1))
		{
			
		$collection=$rw1['collamount'];	
		$discountamount=$rw1['discountamount'];	
		}
			
			$sql_tray=mysqli_query($conn,"SELECT sum(tamount) as return_amount FROM sale_return_header WHERE sale_date<'".$fromdate."' and  customer_id='$customerName' and status=''");
			
		$row_tray=mysqli_fetch_array($sql_tray,MYSQLI_ASSOC);
		
		$sql_master_balance=mysqli_query($conn,"SELECT opening_balance as master_balance FROM customer_master WHERE   id='$customerName' ");
		$row_master_balance=mysqli_fetch_array($sql_master_balance,MYSQLI_ASSOC);
			
						
			$openingbalance=($samount+$row_master_balance['master_balance']) - ($collection+$discountamount+$row_tray['return_amount']);
			
			 
			
			
			$msql3=mysqli_query($conn,"select saleheader.customer_id as cid,saleheader.invoice_no as invno,saleheader.sale_date as date,saleheader.tamount as amt,('Sales') as type,('-') as mode,('-') as discount from saleheader  where saleheader.customer_id ='".$customerName."' && saleheader.sale_date BETWEEN '".$fromdate."' and '".$todate."' and saleheader.status=''
			 
UNION ALL


select srt.customer_id as cid,srt.invoice_no as invno,srt.sale_date as date,srt.tamount as amt,('Return') as type,('-') as mode,('-') as discount from sale_return_header as srt  where srt.customer_id ='".$customerName."' && srt.sale_date BETWEEN '".$fromdate."' and '".$todate."' and srt.status='' 

UNION ALL

select customer_payment_header.customerID as cid,customer_payment_header.cashno as invno,customer_payment_header.collectiondate as date,customer_payment_header.received_amount as amt,('Paid') as type,customer_payment_header.paymenttype as mode,discount as discount from customer_payment_header where customer_payment_header.customerID='".$customerName."' && customer_payment_header.collectiondate BETWEEN '".$fromdate."' and '".$todate."' and  customer_payment_header.status='' order by date ");





        
		$tsales=0;
		$tcollection=0;
		$treturn=0;
		$tdicount=0;
		$count=0;
		while($rw3=mysqli_fetch_array($msql3))
		{ 
		$sale_id_no =  $rw3['invno'];
			if($rw3['type'] == 'Paid'){
				$pro_name = '-';
				$pro_qty  = '-';
				$tcollection=$tcollection + $rw3['amt'];
				$tdicount=$tdicount + $rw3['discount'];
				//$sale_id = $rw3['saleid'];
				//$sale_inv = mysqli_query($conn,"select saleheader.invoice as invno from saleheader where id = '$sale_id'");
				//$sale_id_noo = mysqli_fetch_assoc($sale_inv);
				//sale_id_no  = $sale_id_noo['invno'];
				}
				elseif($rw3['type'] == 'Return')
				{
				$treturn=$treturn + $rw3['amt'];
				
				}
				
				else
				{
					$tsales=$tsales + $rw3['amt'];
					//$sale_id = $rw3['saleid'];
					
					
					}
					
						$sql_tray_return=mysqli_query($conn,"SELECT sum(tamount) as tray_return FROM tray_return_header WHERE sale_date between  '".$fromdate."' and '".$todate."' and  customer_id='$customerName' and status=''");
						
		$row_tray_return=mysqli_fetch_array($sql_tray_return,MYSQLI_ASSOC);
		
		$tray_rtn=$row_tray_return['tray_return'];
			
			$msql4=mysqli_query($conn,"select * from    customer_master where id='".$customerName."'  ");
			
				while($rw4=mysqli_fetch_array($msql4))
		
			{
			$pending=($tsales + $openingbalance) - ($tdicount+$tcollection+$treturn);
			
			
        ?>
        <tbody>
           <tr>
           <td><?php echo ++$count;?></td>
           <td><?php echo $rw3['date'];?></td>
           <td><?php echo $sale_id_no;?></td>
		 
           <td><?php echo $rw3['invno'];?></td>
           <td><?php echo $rw4['cname'];?></td>
           
           <td><?php echo $rw3['type'];?></td>
           <td><?php echo $rw3['mode'];?></td>
           <td><?php echo number_format(round($rw3['discount']),2,'.','');?></td>
           <td><?php echo number_format(round($rw3['amt']),2,'.','');?></td>
           
           </tr> 
                    
           
        </tbody>
        <?php
		}
		}
		?>
        
        <tr>
           
           <td colspan="8" align="right">முன் பாக்கி</td>
           <td><?php echo number_format(round($openingbalance),2,'.','');?></td>
           
           </tr> 
           <tr>
           
           <td colspan="8" align="right">மொத்த விற்பனை</td>
           <td><?php echo number_format(round($tsales),2,'.','');?></td>
           
           </tr>
           
           <tr>
           
           <td colspan="8" align="right">திரும்ப பெற்றது</td>
           <td><?php echo number_format(round($treturn),2,'.','');?></td>
           
           </tr> 
           
           <tr>
           
           <td colspan="8" align="right">பெறப்பட்ட தொகை</td>
           <td><?php echo number_format(round($tcollection),2,'.','');?></td>
           
           </tr>
           
           <td colspan="8" align="right">மொத்த தள்ளுபடி</td>
           <td><?php echo number_format(round($tdicount),2,'.','');?></td>
           
         </tr>
    
    
           
            <tr>
           
           <td colspan="8" align="right">மொத்த பாக்கி</td>
           <td><?php echo number_format(round($pending),2,'.','');?></td>
           
           </tr> 
       
    </table>
   </div>
</div>



    <?php require 'footer.php' ?>

    <script type="text/javascript">var base_url = "<?= $base_url ?>";</script>
   
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js"></script>

    <!--<script>


$(document).ready(function() {

    

            $("#fromDate").datepicker({
        minDate: '-1Y-6M',
        maxDate: '+1Y+6M',
        dateFormat: 'yy-mm-dd',
        onSelect: function (dateStr) {
            var min = $(this).datepicker('getDate'); // Get selected date
            $("#toDate").datepicker('option', 'minDate', min || '0'); // Set other min, default to today
        }
    });

    //toDate

    $("#toDate").datepicker({
        minDate: '1',
        maxDate: '+1Y+6M',
        dateFormat: 'yy-mm-dd',
        onSelect: function (dateStr) {
            var max = $(this).datepicker('getDate'); // Get selected date

            $('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to +18 months

            
        }
    });

            
});

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