<?php
include "../connection/config.php";
if(isset($_POST['add']))
{
    $flag     =  $_POST['flag'];
    $saleid      =  $_POST['saleid'];

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

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

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


}
?>