Skip to content

Commit

Permalink
api beta update v2
Browse files Browse the repository at this point in the history
  • Loading branch information
Undergraduate Student committed Dec 15, 2024
1 parent ecd9f17 commit 501dedf
Show file tree
Hide file tree
Showing 6 changed files with 222 additions and 6 deletions.
45 changes: 45 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const API_URL = "https://users.iee.ihu.gr/~iee2020202/ADISE24_DreamTeam/blokus.php/users/";

// Handle login
$("#loginForm").on("submit", function (event) {
event.preventDefault();

const userId = $("#userId").val();

$.ajax({
url: API_URL + userId,
method: "GET",
success: function (response) {
if (response && response.id) {
// Save user info in sessionStorage
sessionStorage.setItem("loggedInUser", JSON.stringify(response));
window.location.href = "stats.html"; // Redirect to stats page
} else {
$("#errorMessage").text("Invalid User ID").show();
}
},
error: function () {
$("#errorMessage").text("Unable to fetch user data. Please try again.").show();
},
});
});

// Redirect to login if not logged in
if (window.location.pathname.endsWith("stats.html")) {
const loggedInUser = sessionStorage.getItem("loggedInUser");
if (!loggedInUser) {
window.location.href = "login.html";
} else {
const user = JSON.parse(loggedInUser);
$("#userId").text(user.id);
$("#username").text(user.username);
$("#email").text(user.email);
$("#createdAt").text(user.created_at);
}
}

// Logout functionality
$("#logoutBtn").on("click", function () {
sessionStorage.removeItem("loggedInUser");
});

3 changes: 1 addition & 2 deletions blokus.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ function handle_users($method, $input) {
// Handler for 'user' endpoint (show a specific user)
function handle_user($method, $identifier, $input) {
if ($method == 'GET') {
show_user($identifier); // Assuming you have a function to show a specific user
getUserProfile($identifier); // Assuming you have a function to show a specific user
} else {
header('HTTP/1.1 405 Method Not Allowed');
}
Expand All @@ -74,4 +74,3 @@ function handle_status($method) {
}
}
?>

78 changes: 74 additions & 4 deletions lib/users.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,78 @@ function getPathSegments() {
return $segments;
}

// Function to get the database connection


/**
* Retrieve user profile details
*/
function getUserProfile($userId) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "SELECT id, username, email, created_at FROM users WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
echo json_encode($user, JSON_PRETTY_PRINT); // Return the user's profile data as JSON
} else {
echo json_encode(['error' => 'User not found']);
}
} catch (PDOException $e) {
echo json_encode(['error' => 'Error in getUserProfile: ' . $e->getMessage()]);
}
}

/**
* Update user profile details
*/
function updateUserProfile($userId, $username, $email) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$username, $email, $userId]);
return ['success' => $stmt->rowCount() > 0];
} catch (PDOException $e) {
return ['error' => 'Error in updateUserProfile: ' . $e->getMessage()];
}
}

/**
* Delete user account
*/
function deleteUser($userId) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "DELETE FROM users WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId]);
return ['success' => $stmt->rowCount() > 0];
} catch (PDOException $e) {
return ['error' => 'Error in deleteUser: ' . $e->getMessage()];
}
}

/**
* Retrieve user's game statistics
*/
function getUserGameStats($userId) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "SELECT
COUNT(CASE WHEN player1_id = ? AND winner_id = player1_id THEN 1 END) AS wins,
COUNT(CASE WHEN player2_id = ? AND winner_id = player2_id THEN 1 END) AS losses,
COUNT(game_id) AS total_games
FROM games
WHERE player1_id = ? OR player2_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId, $userId, $userId, $userId]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
return ['error' => 'Error in getUserGameStats: ' . $e->getMessage()];
}
}

// RESTful Functions
function show_users() {
$pdo = getDatabaseConnection();
Expand Down Expand Up @@ -47,9 +116,9 @@ function show_user($piece_color) {
// If no additional segment, call show_users()
show_users();
} elseif (count($segments) === 2) {
// If additional segment, call show_user($piece_color)
$piece_color = $segments[1];
show_user($piece_color);
// If additional segment, call getUserProfile($userId)
$userId = $segments[1];
getUserProfile($userId);
} else {
http_response_code(404);
echo json_encode(["error" => "Invalid endpoint"]);
Expand All @@ -62,5 +131,6 @@ function show_user($piece_color) {
http_response_code(404);
echo json_encode(["error" => "Endpoint not found"]);
}

?>

36 changes: 36 additions & 0 deletions login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-4">
<div class="card">
<div class="card-header text-center">
<h4>Login</h4>
</div>
<div class="card-body">
<form id="loginForm">
<div class="form-group mb-3">
<label for="userId">User ID</label>
<input type="number" id="userId" class="form-control" placeholder="Enter your User ID" required>
</div>
<button type="submit" class="btn btn-primary w-100">Login</button>
</form>
<div id="errorMessage" class="text-danger mt-3" style="display: none;"></div>
</div>
</div>
</div>
</div>
</div>

<script src="app.js"></script>
</body>
</html>

33 changes: 33 additions & 0 deletions stats.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Stats</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-6">
<div class="card">
<div class="card-header text-center">
<h4>Your Stats</h4>
</div>
<div class="card-body">
<p><strong>Username:</strong> <span id="usernameDisplay"></span></p>
<p><strong>Total Games Played:</strong> <span id="totalGames"></span></p>
<p><strong>Wins:</strong> <span id="wins"></span></p>
<p><strong>Losses:</strong> <span id="losses"></span></p>
<a href="login.html" id="logoutBtn" class="btn btn-danger w-100">Logout</a>
</div>
</div>
</div>
</div>
</div>

<script src="app.js"></script>
</body>
</html>

33 changes: 33 additions & 0 deletions status.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Stats</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-6">
<div class="card">
<div class="card-header text-center">
<h4>Your Stats</h4>
</div>
<div class="card-body">
<p><strong>ID:</strong> <span id="userId"></span></p>
<p><strong>Username:</strong> <span id="username"></span></p>
<p><strong>Email:</strong> <span id="email"></span></p>
<p><strong>Created At:</strong> <span id="createdAt"></span></p>
<a href="login.html" id="logoutBtn" class="btn btn-danger w-100">Logout</a>
</div>
</div>
</div>
</div>
</div>

<script src="app.js"></script>
</body>
</html>

0 comments on commit 501dedf

Please sign in to comment.