'Unauthorized', 'message' => 'Invalid API Key.'], 401); } } checkApiKey(); $pdo = db(); $method = $_SERVER['REQUEST_METHOD']; switch ($method) { case 'GET': if (isset($_GET['id'])) { // Get single user $id = $_GET['id']; try { $stmt = $pdo->prepare("SELECT id, name, email, created_at, updated_at FROM users WHERE id = :id"); $stmt->execute(['id' => $id]); $user = $stmt->fetch(); if ($user) { sendJsonResponse($user); } else { sendJsonResponse(['error' => 'Not Found', 'message' => 'User not found.'], 404); } } catch (PDOException $e) { sendJsonResponse(['error' => 'Database Error', 'message' => $e->getMessage()], 500); } } else { // Get all users try { $stmt = $pdo->query("SELECT id, name, email, created_at, updated_at FROM users ORDER BY name"); $users = $stmt->fetchAll(); sendJsonResponse($users); } catch (PDOException $e) { sendJsonResponse(['error' => 'Database Error', 'message' => $e->getMessage()], 500); } } break; case 'POST': $data = json_decode(file_get_contents('php://input'), true); if (!$data || empty($data['name']) || empty($data['email']) || empty($data['password'])) { sendJsonResponse(['error' => 'Bad Request', 'message' => 'Name, email, and password are required.'], 400); } $name = $data['name']; $email = $data['email']; $password = password_hash($data['password'], PASSWORD_DEFAULT); try { $stmt = $pdo->prepare("INSERT INTO users (name, email, password) VALUES (:name, :email, :password)"); $stmt->execute([ 'name' => $name, 'email' => $email, 'password' => $password ]); sendJsonResponse(['message' => 'User created successfully', 'id' => $pdo->lastInsertId()], 201); } catch (PDOException $e) { sendJsonResponse(['error' => 'Database Error', 'message' => $e->getMessage()], 500); } break; default: sendJsonResponse(['error' => 'Method Not Allowed', 'message' => '' . $method . ' method is not supported.'], 405); break; }