<?php
// =============================================================
//  GET /api/v1/staff/list
//
//  Staff directory — mirrors app/manage_staffs.php's own SELECT exactly
//  (same five usertypes, same columns, same ordering). Read-only; the
//  write actions (create/update/toggle status/reset password/delete)
//  are their own endpoints in this module, each independently permission-
//  gated the same way the web page's own AJAX actions are.
// =============================================================

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

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

$account = api_authenticate();
api_require_permission('view_all_users');

$staffTypes = ['Admin', 'Chief_Preceptor', 'Preceptor', 'Nurse_Manager', 'In_Charge'];
$ph = implode(',', array_fill(0, count($staffTypes), '?'));
$types = str_repeat('s', count($staffTypes));

$stmt = $conn->prepare("
    SELECT id, firstname, surname, email, phone, gender, usertype, username, grade, designation, profile, status, created_at, last_login
    FROM users
    WHERE usertype IN ($ph)
    ORDER BY created_at DESC
");
$stmt->bind_param($types, ...$staffTypes);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

Api::success([
    'staff' => $rows,
    'can' => [
        'create'     => PermissionManager::sessionCan('create_user'),
        'edit'       => PermissionManager::sessionCan('edit_user'),
        'deactivate' => PermissionManager::sessionCan('deactivate_user'),
        'delete'     => PermissionManager::sessionCan('delete_user'),
        'assign_admin_role' => PermissionManager::sessionCan('assign_role'),
    ],
]);
