<?php 

require_once("config/configDB.php"); 

$saleID         = stripslashes($_POST['edit_id']); 
    $saleinvoice =$_POST['saleinvoice']; 
	
	$productID    = $_POST['productID'];
$new_rate    = $_POST['new_rate'];
$prateinput   = $_POST['prateinput'];
   $itemcount      = count($productID);
   
   $create_date  	= $_POST['saledate']; 
   
   
   $autoinc=mysqli_query($conn,"ALTER TABLE product_rate_hdr CHANGE id id INT(11) NOT NULL AUTO_INCREMENT ");
$autoinc1=mysqli_query($conn,"ALTER TABLE product_rate_update CHANGE id id INT(11) NOT NULL AUTO_INCREMENT ");
   
   $delhdr1=mysqli_query($conn,"update  product_rate_hdr set status='DELETED'  where id='$saleID' and status=''");
$deldtl=mysqli_query($conn,"update  product_rate_update set status='DELETED'  where product_rate_hdr_id='$saleID' and status=''");
   
   $count=0;
$check_query	= mysqli_query($conn,"SELECT count(invoice_no) as counts FROM product_rate_hdr WHERE invoice_no = '$saleinvoice'  and status=''"); // Check the database


while($row = mysqli_fetch_array($check_query)){
$count=$row['counts'];
}
if($count!=0){
// Already Exsist


		echo "<script> alert ('Data Inserted Success.');</script>";
		?>
<script language="javascript">window.location.href = "product_rate_Dashboard.php";</script>
<?php
		

}		
else
{
   
   $sql_hdr  = "INSERT INTO product_rate_hdr (invoice_no, create_date, isdelete,status) VALUES ('$saleinvoice','$create_date', '1','')";



mysqli_query($conn,$sql_hdr);

$last_id = mysqli_insert_id($conn);
   
	
   foreach ($productID as $key => $value) {
   $proid=$productID[$key];
   $prrate=$new_rate[$key];
    
    $query = "UPDATE product_master SET purchase_rate='".$prrate."' WHERE id=".$proid;
    mysqli_query($conn,$query);
	
	
    
	$sqle=mysqli_query($conn,"select * from product_master where id='$proid'");
	while($row=mysqli_fetch_array($sqle))
	{
	$pid=$row['id'];
	$productcode=$row['productcode'];
	$productname=$row['productname'];
	$product_tamil=$row['product_tamil'];
	$qty_type=$row['qty_type'];
	$product_type=$row['product_type'];
	
	$gst=$row['gst'];
	$hsn_code=$row['hsn_code'];
	$prodct_description=$row['prodct_description'];
	
	
	
	$sql  = "INSERT INTO product_rate_update (product_rate_hdr_id,invoice_no,productid,productcode, productname,product_tamil,qty_type,product_type,oldrate, purchase_rate, gst, hsn_code,prodct_description, create_date, isdelete,status) VALUES ('$last_id','$saleinvoice','$pid','$productcode','$productname','$product_tamil','$qty_type','$product_type','$prateinput[$key]','$new_rate[$key]','$gst','$hsn_code','$prodct_description','$create_date', '1','')";



mysqli_query($conn,$sql);
	}
	}
	}
	
	
	
header("Location:product_rate_Dashboard.php");