<?php
// =============================================================
//  GET /api/v1/admin_allocations/unit_list
//
//  Mirrors app/manage_unit_assignment.php's own page-data fetch: every
//  active department→unit week assignment, via getUnitAssignments() —
//  the same function that page itself calls. Search/filter (q,
//  specialty, department query params on the desktop page) are left to
//  the mobile client to apply locally against this same flat list,
//  rather than round-tripping every keystroke.
//
//  Also returns 'trash' — every soft-deleted assignment, mirroring
//  app/trash.php's own "Deleted Unit Assignments" section
//  (getDeletedUnitAssignments()), but with created_by resolved to a
//  name via LEFT JOIN rather than the desktop page's own raw numeric
//  id (a display-only improvement — the underlying data and
//  restore/permanent-delete behaviour are unchanged).
// =============================================================

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');

$trash = $conn->query("
    SELECT duw.id, s.name AS specialty_name, d.department_name,
           u.unit_name, duw.weeks,
           duw.created_by, CONCAT(cb.firstname, ' ', cb.surname) AS created_by_name,
           duw.created_at, duw.deleted_by, duw.deleted_at
    FROM   department_unit_weeks duw
    JOIN   specialty    s ON duw.specialty_id   = s.id
    JOIN   departments d ON duw.department_id = d.id
    JOIN   units       u ON duw.unit_id       = u.id
    LEFT   JOIN users cb ON cb.id = duw.created_by
    WHERE  duw.is_active = 'Inactive'
    ORDER  BY duw.deleted_at DESC
")->fetch_all(MYSQLI_ASSOC);

Api::success(['assignments' => getUnitAssignments($conn), 'trash' => $trash]);
