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

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

$line_num = $_GET['line_num'];
$stock_take_date = $_GET['stock_take_date_text'];

$i=0;
while ($i<$line_num) {
	$count_id = $_GET['count_id_text'.$i];
	$store_item_id = $_GET['store_item_id_text'.$i];
	$counted_qty = $_GET['counted_qty_text'.$i];
	$item_name = $_GET['item_name_text'.$i];
	
	
	$table_name = $_SESSION['db_prefix']."_material_stock_count";
	$saved_query = "SELECT new_stock FROM $table_name WHERE count_id = '".$count_id."' ";
	$saved_result = $con->query($saved_query);
	$row = mysqli_fetch_assoc($saved_result);
	$saved_total = $row['new_stock'];
	
	
	$table_name = $_SESSION['db_prefix']."_material_stock_count";
	$count_update_query = "UPDATE $table_name SET new_stock = '".$counted_qty."' WHERE count_id = '".$count_id."' ";
	$count_update_result = $con->query($count_update_query);
	
	$table_name = $_SESSION['db_prefix']."_store_items";
	$stock_update_query = "UPDATE $table_name SET quantity = '".$counted_qty."' WHERE store_item_id = '".$store_item_id."' ";
	$stock_update_result = $con->query($stock_update_query);
	
	$table_name = $_SESSION['db_prefix']."_store_items";
	$stock_quantity_query = "SELECT quantity AS stock_quantity FROM $table_name WHERE store_item_id = '".$store_item_id."'  ";
	$stock_quantity_result = $con->query($stock_quantity_query);
	$row = mysqli_fetch_assoc($stock_quantity_result);
	$stock_quantity = $row['stock_quantity'];
	
	
	
	$difference = $counted_qty - $saved_total;
	
	if ($difference!=0) {
		
	$table_name4 = $_SESSION['db_prefix']."_item_history";
	$history_query = "INSERT INTO $table_name4 (store_item_id, entry, reference, reference_2, quantity, total, date, entryDate, userId) VALUES ('".$store_item_id."','12','5', '', '".$difference."',  '".$stock_quantity."', '".$entry_date."', '".$entry_date."', '".$_SESSION['username']."')";
	$history_result = $con->query($history_query);
			
	if ($saved_total!=$counted_qty) {
		$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 ('".$entry_date."' ,'".$_SESSION['username']."', '29', '".$item_name."' ,'".$saved_total."','".$counted_qty."','Stock count edit' )";
		$tracking_result = $con->query($tracking_query);
	}
	}
	
	$i++;
}
	
if (isset($_GET['save_close_button']) )
	   { ?>
       <script>
	 		 window.location="../store/store_main.php?date=&branch=&subCatSelect=Tiles";
		</script>
        <?php		 
	   }
	   
if (isset($_GET['save_button']) )
	   {  ?>
       <script>
	        window.location="edit_material_stock_count.php?stock_take_date=<?php echo $stock_take_date?>&show=1";
	   </script>
        <?php		 
	   }
	   ?>