<?php
// =============================================================
//  GET /api/v1/admin_allocations/specialty_department_list
//
//  Mirrors app/specialty_department.php's own page-data fetch: every
//  active specialty→department week allocation (via
//  getSpecialtyDepartmentAllocations()) plus the per-specialty summary
//  cards (via getSpecialtySummary()) that page shows above the form.
//  Gated on 'manage_allocations', which role_permissions confirms is
//  held by Admin only (unlike manage_departments/manage_units/
//  manage_specialties, which Chief_Preceptor also holds).
//
//  Also returns 'trash' — every soft-deleted allocation, mirroring
//  app/trash.php's own "Deleted Specialty-Department Allocations"
//  section (getDeletedSpecialtyDepartments()), 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_allocations');

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

Api::success([
    'allocations' => getSpecialtyDepartmentAllocations($conn),
    'summary' => getSpecialtySummary($conn),
    'trash' => $trash,
]);
