<?php
// =============================================================
//  GET /api/v1/admin_allocations/unit_available?specialty_id=1&department_id=2
//
//  Wraps app/unit_assignment.php's own 'get_specialty_department_summary'
//  action — the specialty-department's allocated/assigned/remaining
//  weeks (getSpecialtyDepartmentSummary()) plus every Active unit not
//  yet assigned under that pair (getAvailableUnitsForSpecialtyDepartment()),
//  used to drive the create form's unit picker and weeks cap once a
//  specialty+department have been chosen.
// =============================================================

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

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

api_authenticate();
api_require_permission('manage_assignments');

$specialtyId = (int)($_GET['specialty_id'] ?? 0);
$departmentId = (int)($_GET['department_id'] ?? 0);
if (!$specialtyId || !$departmentId) {
    Api::error(422, 'ValidationError', 'specialty_id and department_id are required');
}

$summary = getSpecialtyDepartmentSummary($conn, $specialtyId, $departmentId);
if (!$summary) {
    Api::error(404, 'NotFound', 'This specialty is not allocated to this department.');
}

Api::success([
    'summary' => $summary,
    'available_units' => getAvailableUnitsForSpecialtyDepartment($conn, $specialtyId, $departmentId),
]);
