<?php
require_once('config.php');
require_once('f_resize_imagepath.php');

//require_once('f_update_budget.php');

$error_message;
$valid = true;


/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}


$site_cd = $_REQUEST['site_cd'];
$tkn_dvc_id = $_REQUEST['tkn_dvc_id'];
$last_user = $_REQUEST['last_user'];
$Folder = $_REQUEST['folder'];

$sql_tkn_mst = "UPDATE tkn_mst 
					SET tkn_logout = GetDate(),
						tkn_online = '0'							
					WHERE tkn_site =?
					AND tkn_dvc_id = ? 
					AND tkn_user =?
					AND tkn_online = '1'";
		
	
	$params_tkn_mst = array($site_cd,$tkn_dvc_id,$last_user);
	$stmt_tkn_mst = sqlsrv_query( $conn, $sql_tkn_mst,$params_tkn_mst);	
		
if( !$stmt_tkn_mst ) {
	$error_message = "Error update table (tkn_mst)";
	returnError($error_message);
	die( print_r( sqlsrv_errors(), true));
}sqlsrv_free_stmt( $stmt_tkn_mst);


$sql_emp_mst = "select emp_mst_login_id from emp_mst where emp_mst_empl_id = '".$last_user."'";
$stmt_emp_mst = sqlsrv_query( $conn, $sql_emp_mst);	
		
if( !$stmt_emp_mst ) {
	$error_message = "Error update table (emp_mst)";
	returnError($error_message);
	die( print_r( sqlsrv_errors(), true));
}

do {
	while ($row = sqlsrv_fetch_array($stmt_emp_mst, SQLSRV_FETCH_ASSOC)) {	
	
		$LOGINID = $row['emp_mst_login_id'];
	
	}
}while ( sqlsrv_next_result($stmt_emp_mst) );


// Construct the directory path
$directoryToDelete = "C:\\wamp64\\www\\" . $Folder . "\\mobile_image_temp\\temp_" . $LOGINID . "_" . $tkn_dvc_id;

// Try to delete the directory
if (deleteDirectory($directoryToDelete)) {
    //echo "Directory deleted successfully.";
} else {
    //error_log("Error deleting directory: " . $directoryToDelete); // Log the error
    //echo "Error deleting directory.";
}





if( $stmt_tkn_mst) {
	 sqlsrv_commit( $conn );
	 sqlsrv_close( $conn);	
	 returnData();	
} else {
	 sqlsrv_rollback( $conn );
	 $error_message = "Transaction rolled back.<br />";
	 returnError($error_message);
} 




/* if ($valid) {	
	returnData($json);	
}
 */
//sqlsrv_free_stmt( $stmt);


function returnData(){
	
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'You have successfully logged out.');
	
	echo json_encode($returnData);
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'Alert',
	'message' => $error_message,
	'data' => $json);	
	
	echo json_encode($returnData);
		
	exit();
}
 
?>