 <?php
	include 'inc/conx.php';

	$invoice = $_POST['invoice'];
	$id = $_POST['id'];

	$q = $db->query("SELECT * FROM customerinvoice WHERE id = '$id' ");
	$fetchRm = $q->fetchArray();
	$itemName = $fetchRm['item_name'];
	$totalqty = $fetchRm['qty'] * $fetchRm['kg'];

	$sitem  = $db->query("SELECT * FROM itemsetup WHERE item_name = '$itemName' ");
	$fitem  = $sitem->fetchArray();

	$newStock = $fitem['stock'] - $totalqty;
	
	$previousPricenQty = $fitem['purchase_price'] * $fitem['stock'];
	$currentPricenQty = $fetchRm['sell'] * $totalqty;
	$newPrice = ($previousPricenQty - $currentPricenQty) / ($fitem['stock'] - $totalqty);
	
	$update = $db->query("UPDATE itemsetup SET stock = '$newStock', purchase_price = '$newPrice' WHERE item_name = '$itemName' ");


	// $select = $db->query("SELECT * FROM customerinvoice WHERE id = '$id' ");
	// while($fetch = $select->fetchArray()){
	// 	echo $itemName = $fetch['itemDescription'];
	// 	$qty      = $fetch['qty'];
	// 	$rate     = $fetch['rate'];

	// 	$sitem  = $db->query("SELECT * FROM itemsetup WHERE item_name = '$itemName' ");
	// 	$fitem  = $sitem->fetchArray();
	// 	$prST   = $fitem['stock'];
	// 	$prRS	= $fitem['purchase_price'];

	// 	if($fetch['type'] == 'Purchase'){
	// 		$nwST   =  $prST - $fetch['qty'];
	// 		$previousPricenQty = $prRS * $prST;
	// 		$currentPricenQty = $rate * $qty;
	// 		$nwPR = ($previousPricenQty - $currentPricenQty) / ($prST - $qty);

	// 		$update = $db->query("UPDATE itemsetup SET stock = $nwST, purchase_price = $nwPR WHERE item_name = '$itemName' ");
	// 	}
	// 	if($fetch['type'] == 'Sale'){
	// 		$nwST   =  $prST + $fetch['qty'];
	// 		$update = $db->query("UPDATE itemsetup SET stock = $nwST WHERE item_name = '$itemName' ");
	// 	}
	// 	if($fetch['type'] == 'Misc'){
	// 		$nwST   =  $prST - $fetch['qty'];
	// 		$update = $db->query("UPDATE itemsetup SET stock = $nwST WHERE item_name = '$itemName' ");
	// 	}
	// 	if($fetch['type'] == 'Return'){
	// 		$cus_ch = preg_replace('/[^a-z]/', "", strtolower($row['supplierName']));
	// 		if($cus_ch == 'c'){
	// 			$nwST   =  $prST - $fetch['qty'];
	// 		}elseif($cus_ch == 's'){ 
	// 			$nwST   =  $prST + $fetch['qty'];
	// 		}else{
	// 			$nwST   =  $prST - $fetch['qty'];
	// 		}
			
	// 		$update = $db->query("UPDATE itemsetup SET stock = $nwST WHERE item_name = '$itemName' ");
	// 	}

	// 	echo 'Pre st: '. $prST . $fetch['itemDescription'] . ' ' .$fetch['qty'] . ' New ST' . $nwST;
		
	// }
?>