<?php
// =============================================================
//  GET /api/v1/admin_reference/departments_list[?status=Active|Inactive]
//
//  Management list for departments — unlike reference/departments.php
//  (read-only, Active-only, used by every role for pickers), this
//  includes Inactive rows too, since an Admin/Chief_Preceptor needs to
//  see and reactivate a deactivated department. Gated on manage_departments,
//  not just authentication.
// =============================================================

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

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

api_authenticate();
api_require_permission('manage_departments');

$status = (string)($_GET['status'] ?? 'Active');
if (!in_array($status, ['Active', 'Inactive'], true)) $status = 'Active';

$stmt = $conn->prepare("
    SELECT id, department_name, nurse_manager, preceptor, status,
           cancelled_by, cancelled_reason, cancelled_at
    FROM departments
    WHERE status = ?
    ORDER BY department_name
");
$stmt->bind_param('s', $status);
$stmt->execute();
$departments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

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