<?php
// =============================================================
//  GET /api/v1/admin_reference/units_list[?status=Active|Inactive]
//
//  Management list for units — see departments_list.php's header
//  comment for why this is separate from reference/units.php.
// =============================================================

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

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

api_authenticate();
api_require_permission('manage_units');

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

// units.cancelled_by is int(11) (a FK to users.id), unlike
// departments.cancelled_by/specialty.deactivated_by which store the name
// directly — resolve it to a display name here so the API always returns
// a name string, matching what DepartmentAdmin/SpecialtyAdmin already do.
$stmt = $conn->prepare("
    SELECT u.id, u.unit_name, u.in_charge, u.status,
           CONCAT(ub.firstname, ' ', ub.surname) AS cancelled_by,
           u.cancelled_reason, u.cancelled_at
    FROM units u
    LEFT JOIN users ub ON ub.id = u.cancelled_by
    WHERE u.status = ?
    ORDER BY u.unit_name
");
$stmt->bind_param('s', $status);
$stmt->execute();
$units = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

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