query( "SELECT u.userID, u.username, u.role, u.entityID, u.mustChangePassword, u.createdAt, COALESCE(a.location, s.location, '') AS location, c.supervisorID, sv.username AS supervisorUsername FROM users u LEFT JOIN admin a ON a.adminID = u.entityID AND u.role = 'admin' LEFT JOIN supervisor s ON s.supervisorID = u.entityID AND u.role = 'supervisor' LEFT JOIN coach c ON c.coachID = u.entityID AND u.role = 'coach' LEFT JOIN supervisor sv ON sv.supervisorID = c.supervisorID ORDER BY u.role, u.username" )->fetchAll(PDO::FETCH_ASSOC); $supervisors = $pdo->query( "SELECT supervisorID, username, location FROM supervisor ORDER BY username" )->fetchAll(PDO::FETCH_ASSOC); } else { $svNameStmt = $pdo->prepare("SELECT username FROM supervisor WHERE supervisorID = :svid"); $svNameStmt->execute([':svid' => $callerEntityID]); $svName = $svNameStmt->fetchColumn() ?: ''; $stmt = $pdo->prepare( "SELECT u.userID, u.username, u.role, u.entityID, u.mustChangePassword, u.createdAt, '' AS location, c.supervisorID, :svname AS supervisorUsername FROM users u JOIN coach c ON c.coachID = u.entityID AND u.role = 'coach' WHERE c.supervisorID = :svid ORDER BY u.username" ); $stmt->execute([':svid' => $callerEntityID, ':svname' => $svName]); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); $supervisors = []; } qdb_discard($tmpDb, $lockFp); json_success([ 'users' => $users, 'supervisors' => $supervisors, 'callerRole' => $callerRole, ]); } catch (QdbHttpResponse $e) { throw $e; } catch (Throwable $e) { if (isset($tmpDb, $lockFp)) qdb_discard($tmpDb, $lockFp); error_log($e->getMessage()); json_error('SERVER_ERROR', 'Server error', 500); } break; case 'POST': $body = read_json_body(); $username = trim($body['username'] ?? ''); $password = (string)($body['password'] ?? ''); $role = strtolower(trim($body['role'] ?? '')); $location = trim($body['location'] ?? ''); $supervisorID = trim($body['supervisorID'] ?? ''); $mustChange = isset($body['mustChangePassword']) ? (int)(bool)$body['mustChangePassword'] : 1; if ($username === '' || $password === '' || $role === '') { json_error('MISSING_FIELDS', 'username, password, and role are required', 400); } if (!in_array($role, ['admin', 'supervisor', 'coach'], true)) { json_error('INVALID_ROLE', 'role must be admin, supervisor, or coach', 400); } if (strlen($password) < 6) { json_error('PASSWORD_TOO_SHORT', 'Password must be at least 6 characters', 400); } if ($callerRole === 'supervisor' && $role !== 'coach') { json_error('FORBIDDEN', 'Supervisors may only create coaches', 403); } if ($callerRole === 'supervisor') { $supervisorID = $callerEntityID; } if ($role === 'coach' && $supervisorID === '') { json_error('MISSING_FIELDS', 'supervisorID is required for coaches', 400); } try { [$pdo, $tmpDb, $lockFp] = qdb_open(true); $chk = $pdo->prepare("SELECT userID FROM users WHERE username = :u"); $chk->execute([':u' => $username]); if ($chk->fetch()) { qdb_discard($tmpDb, $lockFp); json_error('DUPLICATE', 'Username already exists', 409); } if ($role === 'coach') { $svCheck = $pdo->prepare("SELECT supervisorID FROM supervisor WHERE supervisorID = :sid"); $svCheck->execute([':sid' => $supervisorID]); if (!$svCheck->fetch()) { qdb_discard($tmpDb, $lockFp); json_error('NOT_FOUND', 'Supervisor not found', 400); } if ($callerRole === 'supervisor' && $supervisorID !== $callerEntityID) { qdb_discard($tmpDb, $lockFp); json_error('FORBIDDEN', 'Cannot create coaches for another supervisor', 403); } } $entityID = bin2hex(random_bytes(16)); $userID = bin2hex(random_bytes(16)); $hash = password_hash($password, PASSWORD_DEFAULT); $now = time(); $pdo->beginTransaction(); switch ($role) { case 'admin': $pdo->prepare("INSERT INTO admin (adminID, username, location) VALUES (:id, :u, :loc)") ->execute([':id' => $entityID, ':u' => $username, ':loc' => $location]); break; case 'supervisor': $pdo->prepare("INSERT INTO supervisor (supervisorID, username, location) VALUES (:id, :u, :loc)") ->execute([':id' => $entityID, ':u' => $username, ':loc' => $location]); break; case 'coach': $pdo->prepare("INSERT INTO coach (coachID, supervisorID, username) VALUES (:id, :sid, :u)") ->execute([':id' => $entityID, ':sid' => $supervisorID, ':u' => $username]); break; } $pdo->prepare( "INSERT INTO users (userID, username, passwordHash, role, entityID, mustChangePassword, createdAt) VALUES (:uid, :u, :hash, :role, :eid, :mcp, :now)" )->execute([ ':uid' => $userID, ':u' => $username, ':hash' => $hash, ':role' => $role, ':eid' => $entityID, ':mcp' => $mustChange, ':now' => $now, ]); $pdo->commit(); qdb_save($tmpDb, $lockFp); $svUsername = null; if ($role === 'coach') { [$pdo2, $tmp2, $lk2] = qdb_open(false); $svr = $pdo2->prepare("SELECT username FROM supervisor WHERE supervisorID = :sid"); $svr->execute([':sid' => $supervisorID]); $svUsername = $svr->fetchColumn() ?: null; qdb_discard($tmp2, $lk2); } json_success([ 'userID' => $userID, 'entityID' => $entityID, 'username' => $username, 'role' => $role, 'location' => $location, 'supervisorID' => $role === 'coach' ? $supervisorID : null, 'supervisorUsername' => $svUsername, 'mustChangePassword' => $mustChange, 'createdAt' => $now, ]); } catch (QdbHttpResponse $e) { throw $e; } catch (Throwable $e) { if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack(); if (isset($tmpDb, $lockFp)) qdb_discard($tmpDb, $lockFp); error_log($e->getMessage()); json_error('SERVER_ERROR', 'Server error', 500); } break; case 'DELETE': $body = read_json_body(); $targetUserID = trim($body['userID'] ?? ''); if ($targetUserID === '') { json_error('MISSING_FIELDS', 'userID is required', 400); } if ($targetUserID === ($tokenRec['userID'] ?? '')) { json_error('FORBIDDEN', 'Cannot delete your own account', 400); } try { [$pdo, $tmpDb, $lockFp] = qdb_open(true); $row = $pdo->prepare("SELECT role, entityID FROM users WHERE userID = :uid"); $row->execute([':uid' => $targetUserID]); $target = $row->fetch(PDO::FETCH_ASSOC); if (!$target) { qdb_discard($tmpDb, $lockFp); json_error('NOT_FOUND', 'User not found', 404); } if ($callerRole === 'supervisor') { if ($target['role'] !== 'coach') { qdb_discard($tmpDb, $lockFp); json_error('FORBIDDEN', 'Supervisors can only delete coaches', 403); } $chk = $pdo->prepare("SELECT coachID FROM coach WHERE coachID = :cid AND supervisorID = :svid"); $chk->execute([':cid' => $target['entityID'], ':svid' => $callerEntityID]); if (!$chk->fetch()) { qdb_discard($tmpDb, $lockFp); json_error('FORBIDDEN', 'Coach is not under your supervision', 403); } } $pdo->beginTransaction(); $pdo->prepare("DELETE FROM users WHERE userID = :uid")->execute([':uid' => $targetUserID]); switch ($target['role']) { case 'admin': $pdo->prepare("DELETE FROM admin WHERE adminID = :id")->execute([':id' => $target['entityID']]); break; case 'supervisor': $pdo->prepare("DELETE FROM supervisor WHERE supervisorID = :id")->execute([':id' => $target['entityID']]); break; case 'coach': $pdo->prepare("DELETE FROM coach WHERE coachID = :id")->execute([':id' => $target['entityID']]); break; } $pdo->commit(); qdb_save($tmpDb, $lockFp); json_success([]); } catch (QdbHttpResponse $e) { throw $e; } catch (Throwable $e) { if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack(); if (isset($tmpDb, $lockFp)) qdb_discard($tmpDb, $lockFp); error_log($e->getMessage()); json_error('SERVER_ERROR', 'Server error', 500); } break; default: json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405); }