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

$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 = $con->query($qty_query);
			$row = mysqli_fetch_assoc($qty_result);
			$stock = $row['quantity'];
			$price = $row['price'];
												
			$difference = $quantity- $stock;
			
		    $table_name = $_SESSION['db_prefix']."_stock_count";
		    $report_query = "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."')";
			$report_result = $con->query($report_query);
			
			$table_name3 = $_SESSION['db_prefix']."_store_items";
			$count_query = "UPDATE $table_name3 SET quantity='".$quantity."', stockTake='".$stockTake."' WHERE store_item_id = $store_item_id ";
			$count_result = $con->query($count_query);
			
			
			$table_name4 = $_SESSION['db_prefix']."_item_history";
			$history_query = "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."')";
			$history_result = $con->query($history_query);
	
	$table_name5 = $_SESSION['db_prefix']."_stockloss";
	$stock_loss_query = "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."')";
	$stock_loss_result = $con->query($stock_loss_query);
	
	$table_name = $_SESSION['db_prefix']."_tracking_store";
	$tracking_query = "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."', '' )";
	$tracking_result = $con->query($tracking_query);
	
	$i++;	
	}	
	
   
  header('Location: '."direct_material_stock_report.php?stock_date_select=&stock_date_select2=" );	   
	   ?>