<?php
session_start();
include 'dbc.php';

date_default_timezone_set("Asia/Karachi");
$today=date("Y-m-d");
$month = date("m",strtotime($today));
		$year = date("Y",strtotime($today));
		 $month_name = date("F", mktime(0, 0, 0, $month, 10));
		 $my=$month_name . " " . $year;
		 $t=time();
$username=$_SESSION["username"];
$userid=$_SESSION["userid"];
$invid=$_POST["invid"];
$discount=$_POST["discount"];
$remarks=$_POST["remarks"];

$size = count($_POST['sale_qty']);

$i = 0;
while ($i < $size) {
	$sale_qty= $_POST['sale_qty'][$i];
	$item_name = $_POST['item_name'][$i];
	$item_no = $_POST['item_no'][$i];
	$disc = $_POST['disc'][$i];
	$remarks = $_POST['remarks'][$i];
	
	
	
	  $retail_price = $_POST['retail_price'][$i];
	  $sql5 = "SELECT * FROM items where item_name = '$item_name' and  user_id='$userid'";
$result5=$conn->query($sql5);
$row5 = $result5->fetch_assoc();
$rfid=$row5['rfid'] ;
$barcode=$row5['item_no'] ;
$pid=$row5['id'] ;
$type_name=$row5['type_name'] ;
   $prate=$row5['cost_price'] ;
						 $tamount=$sale_qty * $retail_price;
						 $damount=$tamount * $disc / 100;
						 $totalpamount=$sale_qty * $prate;
						$gamount=$tamount - $damount;
						$totaldiff=$tamount - $totalpamount;
					
if($sale_qty > 0)
{

		$sql = "Insert into invoice_details (id,date,inv_no,item_no,barcode,type_name,item_name,srate,qty,amount,username,user_id,itemcode,prate,pamount,diff,rfid,st,stamount,netamount,remarks)values (null,'$today','$invid','$item_no','$barcode','$type_name','$item_name','$retail_price','$sale_qty','$tamount','$username','$userid','$pid','$prate','$totalpamount','$totaldiff','$rfid','$disc','$damount','$gamount','$remarks')";
$conn->query($sql);
		}					


	++$i;

// do the update and print out some info just to provide some visual feedback


} 
 $sqlinactive = "SELECT * FROM invoice_details where  inv_no='$invid'";
$resultinactive=$conn->query($sqlinactive);
while($rowinactive = $resultinactive->fetch_assoc())
 
  {
 $tmpurchase=$tmpurchase + $rowinactive['amount'];
 $tdamount=$tdamount + $rowinactive['stamount'];
 $tnetamount=$tnetamount + $rowinactive['netamount'];
 
  }
  $tdiscount=$tnetamount * $discount / 100;
  $totalnetamount=$tnetamount - $tdiscount;
//$sql11 = "Insert into expense_voucher (id,date,tr_no,acc_name_dr,discription,amount,user_id,v_type) values (null,'$today','$v_no','$acc_name_dr','$disc','$ledger_amount','$userid','$v_type')";
//mysql_query($sql11) or die("Error : " . mysql_error());

/*$sql2 = "Insert into invoice (id,v_no,date,month_name,cell,username,status,user_id,netamount,cname,disc,stamount)values (null,'$v_no','$today','$my','$areaname','$username','Open','$userid','$tmpurchase','$cname','$disc','$tmpurchase')";
$conn->query($sql2);*/
$sql2 = "UPDATE invoice SET netamount='$tmpurchase',discount='$tdiscount',gamount='$totalnetamount',dis='$discount',st='$disc',stamount='$tdamount',remarks='$remarks' WHERE id='$invid'";
$conn->query($sql2);
header("location:Open_Invoice.php");
?>
