<?php
// =============================================================
//  GET /api/v1/admin_reference/eligible_staff?role=nurse_manager|preceptor|in_charge
//
//  Powers the Nurse Manager / Preceptor / In-Charge picker on the
//  department and unit forms — same eligibility rule as the desktop
//  pages (Admin, plus the specific usertype), same current-assignment
//  count shown alongside each name. Names are matched by full-name
//  string elsewhere in the system (scope resolution is name-based, not
//  a foreign key — see include/session_setup.php), which is exactly
//  why this endpoint returns full names, not ids.
// =============================================================

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

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

api_authenticate();
api_require_any_permission(['manage_departments', 'manage_units']);

$role = (string)($_GET['role'] ?? '');
$map = [
    'nurse_manager' => ['usertype' => 'Nurse_Manager', 'table' => 'departments', 'column' => 'nurse_manager'],
    'preceptor'     => ['usertype' => 'Preceptor',     'table' => 'departments', 'column' => 'preceptor'],
    'in_charge'     => ['usertype' => 'In_Charge',     'table' => 'units',       'column' => 'in_charge'],
];
if (!isset($map[$role])) {
    Api::error(422, 'ValidationError', 'role must be one of: ' . implode(', ', array_keys($map)));
}
$cfg = $map[$role];

$stmt = $conn->prepare("
    SELECT id, CONCAT(firstname, ' ', surname) AS fullname, usertype
    FROM users
    WHERE status = 'Active' AND usertype IN ('Admin', ?)
    ORDER BY firstname, surname
");
$stmt->bind_param('s', $cfg['usertype']);
$stmt->execute();
$people = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$countStmt = $conn->prepare("SELECT COUNT(*) AS cnt FROM {$cfg['table']} WHERE {$cfg['column']} = ? AND status = 'Active'");
foreach ($people as &$p) {
    $countStmt->bind_param('s', $p['fullname']);
    $countStmt->execute();
    $p['current_count'] = (int)($countStmt->get_result()->fetch_assoc()['cnt'] ?? 0);
}
unset($p);
$countStmt->close();

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