<?php
// =============================================================
//  GET /api/v1/reference/units[?department_id=NN]
//
//  Read-only reference data — see departments.php's header comment for
//  why this stays read-only here (management stays on the desktop app).
//  Without department_id, returns every active unit; with it, returns
//  only units allocated to that department via department_unit_weeks
//  (the same join app/units.php and the rotation-creation pages use).
// =============================================================

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

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

api_authenticate();

$departmentId = isset($_GET['department_id']) ? (int)$_GET['department_id'] : null;

if ($departmentId) {
    $stmt = $conn->prepare("
        SELECT DISTINCT u.id, u.unit_name, u.in_charge, u.status
        FROM units u
        JOIN department_unit_weeks duw ON duw.unit_id = u.id
        WHERE u.status = 'Active' AND duw.is_active = 'Active' AND duw.department_id = ?
        ORDER BY u.unit_name
    ");
    $stmt->bind_param('i', $departmentId);
    $stmt->execute();
    $units = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    $units = $conn->query("
        SELECT id, unit_name, in_charge, status
        FROM units
        WHERE status = 'Active'
        ORDER BY unit_name
    ")->fetch_all(MYSQLI_ASSOC);
}

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