<?php
// =============================================================
//  GET /api/v1/admin_allocations/school_unit_list
//
//  Mirrors app/manage_clinical_unit_assignment.php's own page-data
//  fetch: every Active school-unit assignment plus every Inactive
//  (trashed) one, each joined to the unit's own in_charge and the
//  creating/updating/deleting account's name — exactly as that page's
//  two separate queries do.
// =============================================================

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

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

api_authenticate();
api_require_permission('manage_assignments');

$active = $conn->query("
    SELECT sua.id, sua.school_name, u.unit_name, sua.unit_id,
           u.in_charge, sua.duration_value, sua.duration_unit,
           sua.created_at, sua.updated_at,
           CONCAT(uc.firstname, ' ', uc.surname) AS created_by_name,
           CONCAT(uu.firstname, ' ', uu.surname) AS updated_by_name
    FROM school_unit_assignments sua
    JOIN units u        ON sua.unit_id    = u.id
    LEFT JOIN users uc  ON sua.created_by = uc.id
    LEFT JOIN users uu  ON sua.updated_by = uu.id
    WHERE sua.is_active = 'Active'
    ORDER BY sua.school_name ASC, u.unit_name ASC
")->fetch_all(MYSQLI_ASSOC);

$trash = $conn->query("
    SELECT sua.id, sua.school_name, u.unit_name, sua.unit_id,
           u.in_charge, sua.duration_value, sua.duration_unit,
           sua.created_at, sua.deleted_at,
           CONCAT(uc.firstname, ' ', uc.surname) AS created_by_name,
           CONCAT(ud.firstname, ' ', ud.surname) AS deleted_by_name
    FROM school_unit_assignments sua
    JOIN units u        ON sua.unit_id    = u.id
    LEFT JOIN users uc  ON sua.created_by = uc.id
    LEFT JOIN users ud  ON sua.deleted_by = ud.id
    WHERE sua.is_active = 'Inactive'
    ORDER BY sua.deleted_at DESC
")->fetch_all(MYSQLI_ASSOC);

Api::success(['active' => $active, 'trash' => $trash]);
