<?php
include('../include/session.php');

date_default_timezone_set('Africa/Gaborone');
$entry_date = date("Y-m-d H:i:s", time());
$ip_address = $_SERVER['REMOTE_ADDR'];



date_default_timezone_set('Africa/Gaborone');
$entry_date = date("Y-m-d H:i:s", time());
$ip_address = $_SERVER['REMOTE_ADDR'];



$line_num  = $_GET['line_num'];
$i=0;
while ($i<$line_num) {
			$store_item_id  = $_GET['store_item_id_text'.$i];
	        $quantity  = $_GET['counted_qty_text'.$i];
	        
			$category = $_GET['category_text'.$i];
			$subCategory = $_GET['subCategory_text'.$i];
            $date = date("Y-m-d, h:m:s");
			
			date_default_timezone_set('Africa/Gaborone');
			$entryDate = date("Y-m-d H:i:s", time()); 
			$stockTake = 'C';	
			$userId = $_SESSION['username'];
			
			$table_name = $_SESSION['db_prefix']."_store_items";
			$qty_query = "SELECT  quantity, price FROM $table_name WHERE store_item_id = '".$store_item_id."' ";
			$qty_result = mySQL_query($qty_query);
			$stock = mysql_result($qty_result, 0, "quantity");
			$price = mysql_result($qty_result, 0, "price");
						
			$difference = $quantity- $stock;
			
		    $table_name = $_SESSION['db_prefix']."_stock_count";
		    $reportQuery = "INSERT INTO $table_name (date, store_item_id, category, sub_category, old_stock, new_stock, user_name) VALUES ('".$entryDate."' ,'".$store_item_id."','".$category."','".$subCategory."','".$stock."' ,'".$quantity."','".$userId."')";
			execsql($reportQuery);
			
			$table_name3 = $_SESSION['db_prefix']."_store_items";
			$countQuery = "UPDATE $table_name3 SET quantity='".$quantity."', stockTake='".$stockTake."' WHERE store_item_id = $store_item_id ";
			execsql($countQuery);
						
			$table_name4 = $_SESSION['db_prefix']."_item_history";
			$historyQuery = "INSERT INTO $table_name4 (store_item_id, entry, reference, quantity, total, date, entryDate, userId) VALUES ('".$store_item_id."','5','5','".$difference."', '".$quantity."','".$date."','".$entryDate."','".$userId."')";
			$historyResult = mySQL_query($historyQuery);
	
	$table_name5 = $_SESSION['db_prefix']."_stockloss";
	$stockLossQuery = "INSERT INTO $table_name5 (store_item_id, category, sub_category, amount, quantity, total, date, unit_price) VALUES ('".$store_item_id."','".$category."','".$subCategory."', '".$difference."', '".$stock."', '".$quantity."', '".$date."', '".$price."')";
	$stockLossResult = mySQL_query($stockLossQuery);
	
	$table_name = $_SESSION['db_prefix']."_tracking_store";
	$trackingQuery = "INSERT INTO $table_name (entry_date, user_name, action, details_1, details_2, details_3, details_4) VALUES ('".$entryDate."', '".$_SESSION['username']."', '21', '".$store_item_id."', '".$stock."' ,'".$quantity."', '' )";
	$trackingResult = mySQL_query($trackingQuery);
	
	$i++;	
	}	
	
   
   header('Location: '."direct_material_stock_report.php?stock_date_select=&stock_date_select2=" );	   
	   ?>