
<?php 
session_start();
 if(!isset($_SESSION['aid']))
 {
   	echo '<script>location.href="../index.php"</script>';
 }

include "../connection/config.php";
ini_set('display_errors', 0);

//for header
$clquery="select * from company";
$clex=mysqli_query($con,$clquery);
$clf=mysqli_fetch_assoc($clex);

$dateString=$expiry=$clf['expiry'];
$de = new DateTime($dateString);
$formattedDate = $de->format('d/m/Y');

$regdate=$clf['regdate'];
$date= date( 'Y-m-d' );
//for expiry day
$date1 = new DateTime($date);
$date2 = new DateTime($expiry);
$interval = $date1->diff($date2);
$days= $interval->format('%a days');

//get ip
$ipsql="select * from adminlog";
$ipexe=mysqli_query($con,$ipsql);
$ipf=mysqli_fetch_assoc($ipexe);

$category="select * from item_category";
$catexe=mysqli_query($con,$category);

//flag=2
$editflag= (isset($_REQUEST['flag']) ? strip_tags($_REQUEST['flag']): 0);
if ($editflag==2)
{
$saleidedit= (isset($_REQUEST['saleid']) ? strip_tags($_REQUEST['saleid']): 0);
$editsql  =  "select * from sales_reg1 where saleid='$saleidedit'";
$editexe  =   mysqli_query($con,$editsql);
$editfetch=   mysqli_fetch_assoc($editexe);
$cuid     =   $editfetch['cuid'];
$date     =   $editfetch['date'];

$cusql=mysqli_query($con,"select * from customer where cuid='$cuid'");
$cufetch=mysqli_fetch_assoc($cusql);
$customer=$cufetch['name'];
$custreg = $cufetch['regno'];
}


if(isset($_POST['add']))
{
    $flag     =  $_POST['flag'];
    $saleid      =  $_POST['saleid'];

     $date     =  $_POST['date'];
     $custreg  =  $_POST['custreg'];
     $customer =  $_POST['customer'];
     //$name     =  $_POST['name'];
     //$regno    =  $_POST['regno'];
     //$mob      =  $_POST['mob'];
     //$class    =  $_POST['class'];
    // $division =  $_POST['div'];
     //$mob1     =  $_POST['mob1'];
     $item     =  $_POST['item'];
     $price    =  $_POST['amnt'];
     $quantity =  $_POST['quantity'];
     $total    =  $price * $quantity ;

$check_quqntity=mysqli_query($con,"select * from stock where iid='$item'");
$check_quantityfetch=mysqli_fetch_assoc($check_quqntity);
$check_good_stock = $check_quantityfetch['good_stock'];

if($quantity > $check_good_stock)
{
  echo '<script>alert("No Required Quantity.")</script>';
}
else
{
     // for add more items 
     if ($flag==2)
     {
       
    $idsql=mysqli_query($con,"select * from sales_reg1 where saleid='$saleid'");
    $idfet=mysqli_fetch_assoc($idsql);
    $billno=$idfet['sales_billno'];
    
    $sqli="insert into sales_reg2 (saleid,sales_billno,iid,quantity,price,total) values('$saleid','$billno','$item','$quantity','$price','$total')";
    $exee=mysqli_query($con,$sqli);

    //update stock details
    $ssql=mysqli_query($con,"select * from stock where iid='$item'");
    $fsql=mysqli_fetch_assoc($ssql);
    $good_stock=$fsql['good_stock'];
    $stock_out= $fsql['stock_out'];

    $bal_stock    = $good_stock - $quantity; 
    $tot_outstock = $stock_out  + $quantity;

    $stocksql="update stock set stock_out='$tot_outstock',good_stock='$bal_stock' where iid='$item'";
    $stockexe=mysqli_query($con,$stocksql);

    //total amount
    $sum=" SELECT SUM(total) as sumtotal FROM sales_reg2 WHERE sales_billno ='$billno' ";
    $sumexe=mysqli_query($con,$sum);
    $sumfetch=mysqli_fetch_assoc($sumexe);
    $total=$sumfetch['sumtotal'];
     }    

    // for add single items 
    if ($flag==0)
    {
     
     $name     =  $_POST['name'];
     $regno    =  $_POST['regno'];
     $mob      =  $_POST['mob'];
     $class    =  $_POST['class'];
     $division =  $_POST['div'];
     $mob2     =  $_POST['mob1'];

    $cusupdate=mysqli_query($con,"update customer set name='$name',regno='$regno',class='$class',division='$division',mob='$mob',mob2='$mob2' where cuid='$customer'");

    $billsql = "SELECT MAX(sales_billno) AS last_order_code FROM sales_reg1";
    $resultbill = mysqli_query($con, $billsql);
    $rowbill    = mysqli_fetch_assoc($resultbill);
    $last_order_code = $rowbill['last_order_code'];
    
    
    // Generate the new order code by incrementing the last order code by 1 
     $billno = $last_order_code + 1;

    $sql="insert into sales_reg1 (sales_billno,cuid,date) values('$billno','$customer','$date')";
    $exe=mysqli_query($con,$sql);

    $idsql=mysqli_query($con,"select * from sales_reg1 where sales_billno='$billno'");
    $idfet=mysqli_fetch_assoc($idsql);
    $saleid=$idfet['saleid'];
    
    $sqli="insert into sales_reg2 (saleid,sales_billno,iid,quantity,price,total) values('$saleid','$billno','$item','$quantity','$price','$total')";
    $exee=mysqli_query($con,$sqli);

    //update stock details
    $ssql=mysqli_query($con,"select * from stock where iid='$item'");
    $fsql=mysqli_fetch_assoc($ssql);
    $good_stock=$fsql['good_stock'];
    $stock_out= $fsql['stock_out'];

    $bal_stock    = $good_stock - $quantity; 
    $tot_outstock = $stock_out  + $quantity;

    $stocksql="update stock set stock_out='$tot_outstock',good_stock='$bal_stock' where iid='$item'";
    $stockexe=mysqli_query($con,$stocksql);

    //total amount
    $sum=" SELECT SUM(total) as sumtotal FROM sales_reg2 WHERE sales_billno ='$billno' ";
    $sumexe=mysqli_query($con,$sum);
    $sumfetch=mysqli_fetch_assoc($sumexe);
    $total=$sumfetch['sumtotal'];
    }
}   

}

if(isset($_POST['submit']))
{
  $saleid=$_POST['saleid'];
  $nettotal=$_POST['total'];
  $type=$_POST['type'];
  $remark = $_POST['remark'];

  $vsql=mysqli_query($con,"select * from vat");
  $vfet=mysqli_fetch_assoc($vsql);
  $vat=$vfet['tax'];

  $tax = $nettotal * $vat/100;
  $fin_amount = $nettotal + $tax;

  $finamnt_sql="update sales_reg1 set net_amount='$nettotal',vat='$tax',vat_amount='$fin_amount',type='$type',remark='$remark' where saleid='$saleid'";
  $finamnt_exe=mysqli_query($con,$finamnt_sql);

  echo '<script>location.href="billing.php"</script>';
}

?>

<html><head>


    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Admin Console</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.5 -->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
     <!-- DataTables -->
    <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
         folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="dist/css/style.css">
    <link rel="stylesheet" href="css/print.css">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script>
	function isNumeric(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
	return false;
	
	return true;
	}

	</script>
	<style>
  @font-face {
  font-family: "Kerala";
  src: url("KERALI_1.TTF") format("truetype"); 
  }
	</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css" rel="stylesheet">

<script>
$("#name").chosen();
</script>

<!---------------------- select box search --------------------->
<link rel="stylesheet" href="select2.min.css" />
<style>
.select2-dropdown {top: 22px !important; left: 8px !important;}
</style>

<!-------------- end select box search ------------------------->


<!-- <script>
$(document).ready (function(){
$('select[name="customer"]').change(function(){
var nm=$("#name").val();

$.ajax({
     url:"ajax.php",	
     type:"post",
     data:"customer="+nm,
	 success:function(d)
	    {
		$("#abcd").html(d);
		}
});
});
});
</script> -->


<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script>
$(document).ready (function(){
$("#regno").keyup(function(){
var nm=$("#regno").val();
$.ajax({
     url:"ajax.php",	
     type:"post",
     data:"regno="+nm,
	 success:function(d)
	    {
		$("#abcd").html(d);
		}
});
});
});
</script>


<script>
function showUser(str) {
  if (str == "") {
  document.getElementById("abcd").innerHTML = "";
  return;
  } else {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
  document.getElementById("abcd").innerHTML = this.responseText;
  }
  };
  xmlhttp.open("GET","ajaxcustomer.php?q="+str,true);
  xmlhttp.send();
  }
}
</script>

<script>
function showAmount(str) {
  if (str == "") {
  document.getElementById("abc").innerHTML = "";
  return;
  } else {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
  document.getElementById("abc").innerHTML = this.responseText;
  }
  };
  xmlhttp.open("GET","ajaxamount.php?q="+str,true);
  xmlhttp.send();
  }
}
</script>


</head>
      
  <body class="skin-green  sidebar-mini">
    <!-- Site wrapper -->
    <div class="wrapper">
 
      <!-- =============================================== -->

      <!-- Left side column. contains the sidebar -->
      
<header class="main-header">

<div class="row" style="background-color:#4d6c9c; color:#E1EBEE; text-align:center">
<div class="col-md-12"  style="margin-top:10px; ">

<div class="col-md-2"><b style="font-size:20px; float:left;">Billing Software<span style="font-size:10px;">ver1.23</span></b></div>  

<div class="col-md-2">License To : <?php echo $clf['company']; ?> <span style="float:right;">|<span></div>

<div class="col-md-2">Left : <?php echo $days;  ?><span style="float:right;">|<span></div>

<div class="col-md-2">Expiry : <?php echo $formattedDate; ?> <span style="float:right;">|<span></div>

<div class="col-md-2">Powered By : PROGRAMERS Inc <span style="float:right;">|<span></div>

<div class="col-md-1"> Ip - <?php echo $ipf['ip']; ?> </div>
</div><div>

  </header>

<aside class="main-sidebar">
          <!-- sidebar: style can be found in sidebar.less -->
          <section class="sidebar" style="height: auto;">
          <!-- Sidebar user panel -->
          <div class="user-panel"></div>
         
          <ul class="sidebar-menu">
            <li class="treeview "> 
            <a href="home.php"><span>Home</span><i class="fa fa-angle-left pull-right"></i></a></li>
            <li class="treeview "> 
            <a href="#"><span>Master</span><i class="fa fa-angle-left pull-right"></i></a>
            <ul class="treeview-menu">
            <li class=""><a href="item_category.php">Item Category</a></li>
            <li class=""><a href="item_details.php">Item Details</a></li>
            <li class=""><a href="customer.php">Customer Details</a></li>
            </ul> </li> 

            <li class="treeview "> 
            <a href="#"><span>Transaction</span><i class="fa fa-angle-left pull-right"></i></a>
            <ul class="treeview-menu">
            <li class=""><a href="stock_input.php">Stock Input</a></li>
            <li class=""><a href="billing.php">Billing</a></li>
            <!--<li class=""><a href="sales_return.php">Sales Return</a></li>-->
            </ul> </li> 

            <li class="treeview "> 
            <a href="#"><span>Reports</span><i class="fa fa-angle-left pull-right"></i></a>
            <ul class="treeview-menu">
            <li class=""><a href="item_report.php">Item List</a></li>  
            <li class=""><a href="sales_report.php">Sales Register</a></li>  
            <!--<li class=""><a href="sales_return_report.php">Sales Return Register</a></li>  -->
            <li class=""><a href="stock_input_register.php">Stock Translation Register</a></li>   
            <li class=""><a href="stock_register.php">Stock Register</a></li>
            <li class=""><a href="stock_reorder.php">Item Reorder Register</a></li> 
            <li class=""><a href="dead_stock_register.php">Dead Stock Register</a></li>    
            </ul>
            </li> 

            <li class="treeview "> 
            <a href="#"><span>Settings</span><i class="fa fa-angle-left pull-right"></i></a>
            <ul class="treeview-menu">
            <li class=""><a href="company.php">Company Setup</a></li>  
            <li class=""><a href="password.php">Password Reset</a></li>  
            <li class=""><a href="logout.php">Logout</a></li>   
            </ul>
            </li>
            
            </ul>
        </section>
        <!-- /.sidebar -->
      </aside>
      <!-- =============================================== -->

      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper" style="min-height: 700px;">
        <!-- Content Header (Page header) -->
        <section class="content-header"></section>
        <!-- Main content -->
        <section class="content">


		 <div class="row">
<!--------------------------------------------------------------------1st side------------------------------------------------------------------------------------>
            
      <div class="col-md-7">
      <div class="box" id="box_edit" style="margin-top:10px;">

      <div class="box-header with-border"><h3 class="box-title">Billing</h3></div>

      <form class="form-horizontal" action="" method="post" enctype="multipart/form-data" name="form1" autocomplete="off">

      <div class="box-body">
                           
      <input type="hidden" name="flag" value="<?php echo $editflag; ?>"/>
			<input type="hidden" name="saleid" value="<?php echo $saleidedit; ?>"/>
      <input type="hidden" name="bno" value="<?php echo $bno; ?>"/>

      <div class="form-group">
      <!-- <label for="exampleInputEmail1" class="col-sm-1 control-label" >Date</label> -->
      <div class="col-sm-4"><input type="date" class="form-control"  <?php if($editflag==2){ ?> value="<?php echo $date??'';?>" disabled="disabled" <?php }else { ?> value="<?php echo date('Y-m-d'); ?>"<?php }  ?> name="date"  ></div>
      
      <div class="col-sm-2"><input type="text" class="form-control"  <?php if($editflag==2){ ?> value="<?php echo $custreg??'';?>" disabled="disabled" <?php } ?> placeholder ="Regno" name="custreg" id="regno"  ></div>

      <!-- <label for="exampleInputEmail1" class="col-sm-1 control-label" >Student</label> -->
      <div class="col-sm-6">
      <select class="form-control" name="custome" id="name" onchange="showUser(this.value)" <?php if($editflag==2) { ?> disabled="disabled" <?php } ?> >
      <option value="<?php echo $cuid??''; ?>"><?php if($editflag==2) { echo $customer??'';  } else { echo "--Select Customer--"; } ?> </option> 
      <?php $cate=mysqli_query($con,"select * from customer");
      while($cfe=mysqli_fetch_assoc($cate)){ ?> 
      <option value="<?php echo $cfe['cuid']; ?>" ><?php echo $cfe['name']; ?></option>     
      <?php } ?>
      </select>
      </div>
      </div>

      <div id="abcd"></div>  <!---- FOR STUDENT DETAILS------>


      <div class="form-group">
      <!-- <label for="exampleInputEmail1" class="col-sm-1 control-label" > Item </label> -->
      <div class="col-sm-7"> 
      <select class="form-control" name="item" id="itemname" onchange="showAmount(this.value)" >
      <option value="<?php echo $item??''; ?>"><?php if($editflag==3) { echo $item1??'';} else { echo "--Select Item--"; } ?> </option> 
      <?php $cate=mysqli_query($con,"select * from stock");
      while($cfe=mysqli_fetch_assoc($cate)){ 
      $iid=$cfe['iid'];  
      $iidsql=mysqli_query($con,"select * from item_details where iid='$iid' ");
      while($iidcfe=mysqli_fetch_assoc($iidsql)) {?> 
      <option value="<?php echo $iidcfe['iid']; ?>" ><?php echo $iidcfe['item_name']; ?></option>   
      <?php }} ?>
      </select></div>

      <!-- <label for="exampleInputEmail1" class="col-sm-3 control-label" style="margin-left:-10px;" >Price & Quantity</label> -->
      <div class="col-sm-3">
      <div id="abc"></div> <!---------- FOR PRICE------>
      </div>

      <div class="col-sm-1">
      <button type="submit" name="add" style="background-color:#4d6c9c; border-color:#4d6c9c; width:60px; heeight:50px;"  class="btn btn-info"><b>+</b>Add</button>
      </div>

      </div>


      <div class="form-group">
      <label for="exampleInputEmail1" class="col-sm-4 control-label"></label>
      <label for="exampleInputEmail1" class="col-sm-1 control-label" ></label> 
      <!-- <button type="submit" name="add" style="background-color:#4d6c9c; border-color:#4d6c9c; width:60px; heeight:50px;"  class="btn btn-info"><b>+</b>Add</button> -->
      <div class="col-sm-2" id="a">
      </div>

     
      </div> 
      </form>
      <div class="form-group"> <div class="col-sm-6">
      </div></div></div>
      </div>
     </div>

<!------------------------------------------------------------- end 1st side ------------------------------------------------------------------------------------------------------------> 

<!----------------------------------------------------------------- 2nd section--------------------------------------------------------------------------------------------------------->
              
      <div class="col-md-5">
      <div class="box" id="box_edit"  style="margin-top:10px;">
      <div class="box-header with-border">
      <!-- <h3 class="box-title">Customers</h3> -->
      </div>
    
    <table id="example1" class="table table-bordered table-striped" align="center">
    <thead>
    <tr style=" background-color:#fff; color:#4d6c9c;">
    <th style="width:300px;"> Item </th>
    <th> Qty </th>
    <th> Price </th>
    <th> Amount </th>
    <!-- <th> Action </th> -->
    </tr> </thead>

<?php
$bill = $billno??'';

if ($editflag==2)
{
$saleidedit= (isset($_REQUEST['saleid']) ? strip_tags($_REQUEST['saleid']): 0);

$sql= mysqli_query($con,"select * from sales_reg2 where saleid='$saleidedit'");
      while($fetch=mysqli_fetch_assoc($sql)){ 
      $saleid = $fetch['saleid'];
      $iid=$fetch['iid'];
$isql=mysqli_query($con,"select * from item_details where iid='$iid' ");
$ifet=mysqli_fetch_assoc($isql);
$item= $ifet['item_name'];
?>
<tr>
  <td> <?php echo $item; ?> </td>
  <td> <?php echo $fetch['quantity']; ?> </td>
  <td> <?php echo $fetch['price']; ?> </td>
  <td> <?php echo $fetch['total']; ?> </td>
  <!-- <td> <a href="delete_bill.php?iid=<?php echo $iid; ?>&qty=<?php echo $fetch['quantity']; ?>&saleid=<?php echo $saleid; ?>&flag=3"><i class="fa fa-trash-o" style="color:#4d6c9c;"></i></a></td> -->
</tr>
<?php }

// $sd="select * from sales_reg1 where saleid='$saleidedit' ";
// $sdex=mysqli_query($con,$sd);
// $sdf = mysqli_fetch_assoc($sdex);
                
// $cuid = $sdf['cuid']; 
// $bno  = $sdf['sales_billno']; 

// $csql=mysqli_query($con,"select * from customer where cuid='$cuid'");
// $cexe=mysqli_fetch_assoc($csql);
// $customer = $cexe['name'];

}
else
{
  $sql= mysqli_query($con,"select * from sales_reg2 where sales_billno='$bill'");
      while($fetch=mysqli_fetch_assoc($sql)){ 
      $saleid = $fetch['saleid']; 
      $iid=$fetch['iid'];
      $isql=mysqli_query($con,"select * from item_details where iid='$iid' ");
      $ifet=mysqli_fetch_assoc($isql);
      $item= $ifet['item_name'];?>
<tr>
  <td> <?php echo $item; ?> </td>
  <td> <?php echo $fetch['quantity']; ?></td>
  <td> <?php echo $fetch['price']; ?> </td>
  <td> <?php echo $fetch['total']; ?> </td>
  <!-- <td> <a href="delete_bill.php?iid=<?php echo $iid; ?>&qty=<?php echo $fetch['quantity']; ?>&saleid=<?php echo $saleid; ?>&flag=2"><i class="fa fa-trash-o" style="color:#4d6c9c;"></i></a></td> -->
</tr>
<?php } }  

?>
<tr><td colspan="4"><a href="billing.php?saleid=<?php echo $saleid??'' ; ?>&flag=2"><i class="fa fa-plus" aria-hidden="true" style="color:#4d6c9c;"></i></a></td></tr>
</table>

<!---------  total amount form -------->

<form action="" method="post">
<div class="box-body">
<div class="form-group" > <div class="col-sm-4">
<textarea name="remark" placeholder="Remark" style="width:170px;"></textarea></div></div> 

<div class="form-group" >
<div class="col-sm-6">
  
<input type="hidden" name="saleid" value="<?php echo  $saleid??'' ; ?>"> <div>
<div class="col-sm-1">
<input type="text" class="form-control" name="total" value="<?php echo  $total??'' ; ?>" style="width:60px;" readonly></div>
<div class="col-sm-2">
<select class="form-control" name="type"  style="width:100px; margin-left:40px;">
<option>Cash</option>
<option>Bank</option>
<option>Other</option></select></div>

<div class="col-sm-2">
<button type="submit" name="submit" class="btn btn-info" style="background-color:#4d6c9c; border-color:#4d6c9c; margin-left:120px;">Submit</button></div> </div>
</form>

<!--------- end total amount form -------->

</div>
</div> </div> </div>
<!--------------------------------------------------------------------------end 2nd section-------------------------------------------------------------------------->
</div>


<!-------------------------------------------------------------2nd row--------------------------------------------------------------------------------------------------->
<div class="row">
<div class="col-md-12">

<div class="box" id="box_edit" style="margin-top:10px;">

<div class="col-md-6" style="margin-top:10px; margin-bottom:10px; position:relative; left:965px;">
<form action="" method="post">
<div class="col-md-4">
<input type="text" class="form-control" name="bsearch" placeholder="Billno"></div>

<div class="col-md-2">
<button type="submit" name="search" style=" background:white; border-color:white; color:#4d6c9c;"><i class="fa fa-search" style="font-size:25px;"></i></button> </div>

</form>
</div>

<table id="example1" class="table table-bordered table-striped" align="center" style="margin-left:20px;">
    <thead>
    <tr style=" background-color:#fff; color:#4d6c9c;">
    <th>#</th>
    <th> Date </th>
    <th> Bill</th>
    <th> Customer </th>
    <th> Count </th>
    <th> Amount </th>
    <th> Vat </th>
    <th> Net Amount </th>
    <th style="width:300px;">Remark</th>
    <th>Invoice</th>
    </tr> </thead>

<?php

if(isset($_POST['search']))
{
$billsearch=$_POST['bsearch'];
include "config1.php";
$sqli = "select count(saleid) as totalcount,sales_billno,total from sales_reg2 where sales_billno='$billsearch' GROUP BY sales_billno  order by saleid desc";
$stmt = $pdo->query($sqli);
$data = $stmt->fetchAll();
// Initialize counter
$serial = count($data);

  
foreach ($data as $billfetch) { 

$billno = $billfetch['sales_billno'];

$billsql1=mysqli_query($con,"select * from sales_reg1 where sales_billno='$billno'");
$billfet=mysqli_fetch_assoc($billsql1);
$salesid=$billfet['saleid'];
$cuid= $billfet['cuid'];
$date= date('d-m-Y', strtotime($billfet['date']));
$tot_amount= $billfet['net_amount'];
$vat=$billfet['vat'];
$vat_amount=$billfet['vat_amount'];
$remarks=$billfet['remark'];

$csql=mysqli_query($con,"select * from customer where cuid='$cuid'");
$cfet=mysqli_fetch_assoc($csql);
$cust=$cfet['name'];

?>
    <tr>
    <td><?php echo  $serial-- ?></td>
    <td><?php echo $date; ?></td>
    <td><?php echo $billno; ?></td>
    <td><?php echo $cust; ?></td>
    <td><?php echo $billfetch['totalcount']; ?></td>
    <td><?php echo $tot_amount; ?></td>
    <td><?php echo $vat; ?> </td>
    <td><?php echo $vat_amount; ?></td>
    <td><?php echo $remarks; ?></td>
    <td>
      <a href="billedit.php?saleid=<?php echo $salesid; ?>&billno=<?php echo $billno; ?>" class="btn btn-success">Edit</a>
      <a href="vat_invoice.php?saleid=<?php echo $salesid; ?>&billno=<?php echo $billno; ?>" class="btn btn-info">Vat</a>
      <a href="nonvat_invoice.php?saleid=<?php echo $salesid; ?>&billno=<?php echo $billno; ?>" class="btn btn-primary">Bill</a></td>
    </tr>
<?php
}
}

else
{


// PAGINATION
$num_per_page=20;
if(isset($_GET["page"]))
  {
$page=$_GET["page"];
  }
else 
  {
$page=1;
  }
$start_from=($page-1) * 20;


include "config1.php";
$sqli = "select count(saleid) as totalcount,sales_billno,total from sales_reg2 GROUP BY sales_billno  order by saleid desc limit $start_from,$num_per_page";
$stmt = $pdo->query($sqli);
$data = $stmt->fetchAll();
// Initialize counter
$serial = count($data);

  
foreach ($data as $billfetch) { 

$billno = $billfetch['sales_billno'];

$billsql1=mysqli_query($con,"select * from sales_reg1 where sales_billno='$billno'");
$billfet=mysqli_fetch_assoc($billsql1);
$salesid=$billfet['saleid'];
$cuid= $billfet['cuid'];
$date= date('d-m-Y', strtotime($billfet['date']));
$tot_amount= $billfet['net_amount'];
$vat=$billfet['vat'];
$vat_amount=$billfet['vat_amount'];
$remarks=$billfet['remark'];

$csql=mysqli_query($con,"select * from customer where cuid='$cuid'");
$cfet=mysqli_fetch_assoc($csql);
$cust=$cfet['name'];

?>
    <tr>
    <td><?php echo  $serial-- ?></td>
    <td><?php echo $date; ?></td>
    <td><?php echo $billno; ?></td>
    <td><?php echo $cust; ?></td>
    <td><?php echo $billfetch['totalcount']; ?></td>
    <td><?php echo $tot_amount; ?></td>
    <td><?php echo $vat; ?> </td>
    <td><?php echo $vat_amount; ?></td>
    <td><?php echo $remarks; ?></td>
    <td>
      <a href="billedit.php?saleid=<?php echo $salesid; ?>&billno=<?php echo $billno; ?>" class="btn btn-success">Edit</a>
      <a href="vat_invoice.php?saleid=<?php echo $salesid; ?>&billno=<?php echo $billno; ?>" class="btn btn-info">Vat</a>
      <a href="nonvat_invoice.php?saleid=<?php echo $salesid; ?>&billno=<?php echo $billno; ?>" class="btn btn-primary">Bill</a></td>
    </tr>
<?php } }  ?>    

</table>

<?php
//number pagination code 
$sqlp="select count(saleid) as totalcount,sales_billno,total from sales_reg2 GROUP BY sales_billno  order by saleid desc";
$exep=mysqli_query($con,$sqlp);
 $total_records=mysqli_num_rows($exep);
//echo $total_records;
 $total_pages=ceil($total_records/$num_per_page);
//echo $total_pages;  
                       
for($i=1; $i<=$total_pages; $i++)
{
echo "<b><a href='billing.php?page=".$i."' class='btn'>".$i."</a></b>"; echo " ";
}  ?>

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

</div> 
<!-- /.box -->
        
</section><!-- /.content -->
</div><!-- /.content-wrapper -->

  <footer class="main-footer"><strong>Copyright © 2023 <a href="javascript:void(0)"> Perfect Uniform Llc </a></strong> All rights reserved.</footer>

    <!-- ./wrapper -->

    <!-- jQuery 2.1.4 -->
    <script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
    <!-- Bootstrap 3.3.5 -->
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <!-- SlimScroll -->
    <script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
    <!-- FastClick -->
    <script src="plugins/fastclick/fastclick.min.js"></script>
    <!-- AdminLTE App -->
    <script src="dist/js/app.min.js"></script> 
 <!--<script>
 	function displayEdit(id)
	{
		$.ajax({
			type: "POST",
			url: "country_edit.php",
			data:{country_id: id},
			success: function(data){
				$('#box_edit').html(data);
			}
		});
	}
 </script>-->

<!----------------search in select box---------------> 
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script src="select2.min.js"></script>
<script>
$("#itemname").select2( {
	placeholder: "Select Item",
	allowClear: true
	} );
</script>

<script>
$("#name").select2( {
	placeholder: "Select Student",
	allowClear: true
	} );
</script>
<!----------------end search in select box---------------> 
</body></html>