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

	$today = date("Y-m-d");
	$d = date("d");
	$m = date("m");
	$y = date("Y");
	
	$user_id = $_SESSION['username'];
	date_default_timezone_set('Africa/Gaborone');
    $entryDate = date("Y-m-d H:i:s", time()); 
	
			
	$table_name1 = $_SESSION['db_prefix']."_loans_lines_temp";
	$table_name2 = $_SESSION['db_prefix']."_loans_lines";
    $copy_query = "INSERT INTO $table_name2 (loans_id, reference_date, reference, reference_no, amount_debit ) SELECT loans_id, reference_date, reference, reference_no, amount_debit  FROM $table_name1 WHERE loans_id = '".$_SESSION['loans_id']."' AND user_name = '".$_SESSION['username']."' ";	
	execsql($copy_query);	
	
	$table_name = $_SESSION['db_prefix']."_loans_lines_temp";
	$return_query = "SELECT SUM(amount_debit) AS tot_amount_debit  FROM $table_name WHERE loans_id = '".$_SESSION['loans_id']."' GROUP BY loans_id AND user_name = '".$_SESSION['username']."' ";
	$return_result = mySQL_query($return_query);
	$return = mysql_result($return_result, 0, "tot_amount_debit");
	
	$table_name = $_SESSION['db_prefix']."_loans";
	$returned_amount_query = "UPDATE $table_name SET returned_amount = returned_amount+'".$return."' WHERE loans_id = '".$_SESSION['loans_id']."' ";
	execsql($returned_amount_query);
	
	$table_name = $_SESSION['db_prefix']."_tracking_hr";
   $trackingQuery = "INSERT INTO $table_name (entry_date, user_name, action, details_1, details_2, details_3, details_4) VALUES ('".$entryDate."' ,'".$_SESSION['username']."', '28', '".$_SESSION['emp_id']."' ,'".$_SESSION['loans_id']."','".$return."','' )";
   $trackingResult = mySQL_query($trackingQuery);
	
	if (isset($_GET['new_button']) )
	   {
		 $action='loansReturnWiz0.php';
	   }
		 
	if (isset($_GET['finish_button']) )
	  {
		$action='loans_list.php?date=0&emp_id=';
	  }
	
	$table_name = $_SESSION['db_prefix']."_loans_lines_temp";
	$delete_query = "DELETE FROM $table_name WHERE  user_name = '".$_SESSION['username']."'   "; 
	execsql($delete_query);
	
	
	 $_SESSION['emp_id']="";
     $_SESSION['amount'] = "0.00";
	 $_SESSION['loans_id'] = "";
	 $_SESSION['loans_id'] = "";
	 $_SESSION['cash_balance'] = 0;
	 $_SESSION['outstanding'] = 0;
	 $_SESSION['issued_by'] = "";
	 $_SESSION['issue_date'] = date('Y-m-d');
     $_SESSION['employee_name'] = "";
	 $_SESSION['use'] = "";
	 $_SESSION['notes'] = "";

	 
?>

<script language="javascript" type="text/javascript">
        <!--
		  window.location="<?php echo $action ?> ";
        -->
       </script>



