<?php
// =============================================================
//  GET /api/v1/credentials/people?owner_table=users|rotation_nurses|clinical_students
//
//  Owner picker for the Add/Edit Credential form — mirrors
//  app/manage_credentials.php's own $people_by_table query exactly
//  (Active accounts only, ordered by first name; small hospital, no
//  pagination needed).
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Api::error(405, 'MethodNotAllowed', 'Use GET');
}

api_authenticate();
api_require_permission('edit_user');

$ownerTable = (string)($_GET['owner_table'] ?? '');
if (!in_array($ownerTable, ['users', 'rotation_nurses', 'clinical_students'], true)) {
    Api::error(422, 'ValidationError', 'owner_table must be users, rotation_nurses, or clinical_students');
}

$stmt = $conn->prepare("SELECT id, CONCAT(firstname, ' ', surname) AS name FROM `$ownerTable` WHERE status = 'Active' ORDER BY firstname");
$stmt->execute();
$people = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

Api::success(['people' => $people]);
