<?php
session_start();
ob_start();
require "../model/configuration.php";
/* @var $sion type */
$sion = $_POST['sion'];
$type=$_POST['ptype'];
if (isset($_POST['save_purchase'])) 
{
    if (isset($_SESSION['purchase']) && $_SESSION['purchase'] == 'Purchase') 
	{
        $result = $db->execute("SELECT * FROM transaction_number");
        $row = $result->fetch_assoc();
        $trno = $row['trnno'];
        $nwtnno = $trno + 1;
        $db->execute("update transaction_number set trnno='$nwtnno'");
        $date = date("Y-m-d");
        $prdqty = $db->execute("select * from purchase_temp where permission='".$sion."'");
        while ($tqty = $prdqty->fetch_assoc()) 
		{
  $db->execute("INSERT INTO master_purchase(vendr_id,invoice_date,invoice_no,product_code,product_name,gsm,width,length,price,quantity,discount,tax,permission,entrydate,trnno,user,paper,type) VALUES('" . $tqty['vendr_id'] . "','" . $tqty['invoice_date'] . "','" . $tqty['invoice_no'] . "','" . $tqty['product_code'] . "','" . $tqty['product_name'] . "','" . $tqty['gsm'] . "','" . $tqty['width'] . "','" . $tqty['length'] . "','" . $tqty['price'] . "','" . $tqty['quantity'] . "','" . $tqty['discount'] . "','" . $tqty['tax'] . "','" . $tqty['permission'] . "','" . $tqty['entrydate'] . "','" . $trno . "','".$_SESSION['UNAME']."','" . $tqty['paper'] . "','".$type."')");

$stock=$db->execute("SELECT * from stock_master where product_code='".$tqty['product_code']."' and delet='0'");
$stock_qty=$stock->num_rows;
    if($stock_qty>0){
        $st_val=$stock->fetch_assoc();
        $ttqty=$st_val['quantity']+$tqty['quantity'];
        $db->execute("UPDATE stock_master set quantity='$ttqty' where product_code='".$tqty['product_code']."' and delet='0' ");
    }

    else{

        $db->execute("INSERT INTO stock_master(product_code,product_name,quantity,type) VALUES('" . $tqty['product_code'] . "','" . $tqty['product_name'] . "','" . $tqty['quantity'] . "','" . $tqty['paper'] . "') ");
    }
        }
        
        $db->execute("delete from purchase_temp where permission='$sion'");
    }
    unset($_SESSION['purchase']);
}
header("location:../Pages/purchase_page.php");
?>