
<?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);

//------------------------------------------- End of header -------------------------------------------->

$saleid = $_GET['saleid'];
$billno = $_GET['billno'];

$sql=mysqli_query($con,"select * from sales_reg1 where saleid='$saleid'");
$fetch=mysqli_fetch_assoc($sql);
$cuid = $fetch['cuid'];
$date = $fetch['date']; 
$type = $fetch['type']; 
$remark = $fetch['remark']; 

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

if(isset($_POST['update']))
{
 $sl_id = $_POST['sl_id']; 
 $item  = $_POST['i']; 
 $quantity = $_POST['q']; 

    // update stock count 
    $stocksql = mysqli_query($con,"select * from sales_reg2 where sl_id='$sl_id'");
    $stockfet = mysqli_fetch_assoc($stocksql);
    $old_quantity = $stockfet['quantity'];
    $old_item = $stockfet['iid'];

    $itemsql= mysqli_query($con,"select * from stock where iid='$old_item' ");
    $itemfet= mysqli_fetch_assoc($itemsql);
    $good_stock = $itemfet['good_stock'];
    $stock_out = $itemfet['stock_out'];

    if($quantity > $old_quantity)
    {
      $diff = $quantity - $old_quantity;
      $new_good_stock = $good_stock - $diff;
      $new_stock_out = $stock_out  + $diff;

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

    if($quantity < $old_quantity)
    {
      $diff = $old_quantity - $quantity ;
      $new_good_stock = $good_stock + $diff;
      $new_stock_out = $stock_out  - $diff;

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

// To, if item to be change , update the stock details on that item
if ($old_item != $item)
{

    //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);


    $ossql=mysqli_query($con,"select * from stock where iid='$old_item'");
    $osfsql=mysqli_fetch_assoc($ossql);
    $g_stock = $osfsql['good_stock'];
    $stock_o  = $osfsql['stock_out'];

    $b_stock    = $g_stock - $quantity; 
    $t_outstock = $stock_o  + $quantity;

    $stocksql2="update stock set stock_out='$t_outstock',good_stock='$b_stock' where iid='$item'";
    $stockexe2=mysqli_query($con,$stocksql2);
}

// update sales tables sales_reg1 and sales_reg2
$itemprice = mysqli_query($con,"select * from item_details where  iid='$item' ");
$itempricefet = mysqli_fetch_assoc($itemprice); 
$price = $itempricefet['item_price'];
$total = $price * $quantity;

$supdate=" update sales_reg2 set iid='$item',quantity='$quantity',price='$price',total='$total' where sl_id='$sl_id' ";
$exupdate=mysqli_query($con,$supdate);

    //total amount of purchase
    $sum=" SELECT SUM(total) as sumtotal FROM sales_reg2 WHERE saleid ='$saleid' ";
    $sumexe=mysqli_query($con,$sum);
    $sumfetch = mysqli_fetch_assoc($sumexe);
    $nettotal = $sumfetch['sumtotal'];
 
    $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' where saleid='$saleid'";
    $finamnt_exe=mysqli_query($con,$finamnt_sql);
}
?>

<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">
<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>
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","ajax_edit_amount.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-8">
      <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">

      <div class="form-group">
      <div class="col-sm-3"><input type="date" class="form-control" readonly value="<?php echo $date;?>" name="date"  ></div>
      
      <div class="form-group">
      <div class="col-sm-3"><input type="text" class="form-control" readonly  value="Bill No - <?php echo $billno;?>"  name="billno"  ></div>
      
  
      <div class="col-sm-5">
      <select class="form-control" name="customer"  onchange="showUser(this.value)" readonly>
      <option value="<?php echo $cuid??''; ?>"> <?php echo $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>
      </form>
<?php $rowsql=mysqli_query($con,"select * from sales_reg2 where saleid='$saleid'");
while($rowfet=mysqli_fetch_assoc($rowsql)) { 
$iid     = $rowfet['iid']; 
$price   = $rowfet['price'];
//$quantity= $rowfet['quantity'];
$sl_id   = $rowfet['sl_id'];


$iidsql=mysqli_query($con,"select * from item_details where iid='$iid' ");
$iidcfe=mysqli_fetch_assoc($iidsql) ;
$item=$iidcfe['item_name'];  ?>

<form class="form-horizontal" action="" method="post" enctype="multipart/form-data" name="form1" autocomplete="off">
      
      <input type="hidden" class="form-control" name="sl_id" value="<?php echo $sl_id; ?>"  style="width:70px;">

      <div class="form-group">
      <label for="exampleInputEmail1" class="col-sm-1 control-label" >  </label>
      <div class="col-sm-6">  <select class="form-control itemname" name="i" readonly>
      <option value="<?php echo $iid ; ?>" > <?php echo $item; ?></option>  
      <?php  
      $stocksql=mysqli_query($con,"select * from stock");
      while($stockfe=mysqli_fetch_assoc($stocksql)) { 
      $siid = $stockfe['iid']; 
      $iidsql=mysqli_query($con,"select * from item_details where iid='$siid' ");
      $iidcfe=mysqli_fetch_assoc($iidsql) ?> 

      <!-- <option value="<?php echo $iidcfe['iid']; ?>" ><?php echo $iidcfe['item_name']; ?></option> -->

      <?php } ?>
      </select></div>

      <div class="col-sm-2"><input type="number" class="form-control" name="q" value="<?php echo $rowfet['quantity']; ?>"  style="width:70px;"></div>
      <div class="col-sm-2"><button type="submit" name="update" style="background-color:#4d6c9c; border-color:#4d6c9c; width:70px; margin-left:-28; " class="btn btn-info"><i class="fa fa-check"></i></button>
      <a href="delete_bill.php?iid=<?php echo $iid; ?>&qty=<?php echo $rowfet['quantity']; ?>&saleid=<?php echo $saleid; ?>&billno=<?php echo $billno; ?>"><i class="fa fa-trash-o" style="color:#4d6c9c; margin-bottom:-35px; margin-left:15px;"></i></a></div>

      </form>   
      </div>
<?php } ?>

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

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


<!-------------------  MORE ADD OPTION ------------------->
<div class="row">
<div class="col-md-8">
<div class="box" id="box_edit" style="margin-top:10px;">

<div class="box-header with-border"><h3 class="box-title">Add More Item</h3></div>

<div class="box-body">

<form action="" method="post">
<div class="form-group">

      <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>

      <div class="col-sm-4">
      <div id="abc"></div> <!---------- FOR PRICE------>
      </div>

      <div class="col-sm-1">
      <button type="submit" name="add" style="background-color:#4d6c9c; border-color:#4d6c9c; color:white;">Add</button>
      </div>
</div>
</form><br>

<div class="form-group">
<form action="" method="post">
<div class="col-sm-1">
<select class="form-control" name="type" style="width:200px; margin-left:0px; ">
<option><?php echo $type; ?></option>
<option>Cash</option>
<option>Bank</option>
<option>Other</option>
</select>
</div>

<div class="col-sm-4">
<textarea class="form-control" name="r" style="margin-left:148px;"><?php echo $remark; ?></textarea>
</div>

<div class="col-sm-1"><button type="submit" name="s" style="background-color:#4d6c9c; border-color:#4d6c9c; width:40px; margin-left:435; " class="btn btn-info"><i class="fa fa-check"></i></button></div>
</form> </div>

<?php 
if(isset($_POST['s']))
{
  $t=$_POST['type'];
  $r=$_POST['r'];
  $typesql = "update sales_reg1 set type='$t',remark='$r' where saleid='$saleid' ";
  $typeexe= mysqli_query($con,$typesql);
}
?>



<?php 
if(isset($_POST['add']))
  {
      $item     = $_POST['item'];
      $amnt     = $_POST['amnt'];
      $quantity = $_POST['quantity'];
      $total    = $amnt * $quantity;

      $inssql = "insert into sales_reg2(saleid,sales_billno,iid,quantity,price,total) values('$saleid','$billno','$item','$quantity','$amnt','$total')";
      $insexe = mysqli_query($con,$inssql) ;

      $selsql= mysqli_query($con,"select * from sales_reg1 where saleid='$saleid'");
      $fetsql = mysqli_fetch_assoc($selsql);
      $net_amount = $fetsql['net_amount'];

      $nettotal = $net_amount + $total;

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

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

      $upsql= "update sales_reg1 set net_amount='$nettotal',vat='$tax',vat_amount='$fin_amount' where saleid='$saleid'";
      $upexe = mysqli_query($con,$upsql);

      // calculation ok -- stock count remaining 

      $stocksql = mysqli_query($con,"select * from stock where iid='$item'");
      $stockfet = mysqli_fetch_assoc ($stocksql); 
      $good_stock = $stockfet['good_stock'];
      $stock_out = $stockfet['stock_out'];

      $gstock = $good_stock - $quantity;
      $ostock = $stock_out  + $quantity;

      $up_stock_cout = "update stock set good_stock='$gstock',stock_out='$ostock' where iid='$item'";
      $up_stock_out_exe = mysqli_query($con,$up_stock_cout);

  }
?>

</div>

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


<!--------------------------------------------------------------------------end 2nd section-------------------------------------------------------------------------->
</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>