<?php
// =============================================================
//  POST /api/v1/admin_allocations/school_unit_restore
//
//  Wraps app/manage_clinical_unit_assignment.php's own
//  'restore_school_unit' action — refuses to restore if an Active
//  assignment already exists for the same school+unit pair (which can
//  happen if a new one was created after this one was trashed).
//
//  Body: { "id": 5 }
// =============================================================

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

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

$account = api_authenticate();
api_require_permission('manage_assignments');

$body = Api::body();
$id = (int)($body['id'] ?? 0);
if (!$id) Api::error(422, 'ValidationError', 'Invalid ID');

$chk = $conn->prepare("
    SELECT sua.id FROM school_unit_assignments sua
    JOIN school_unit_assignments target ON target.id = ?
    WHERE LOWER(sua.school_name) = LOWER(target.school_name)
      AND sua.unit_id     = target.unit_id
      AND sua.is_active   = 'Active'
      AND sua.id         != ?
");
$chk->bind_param('ii', $id, $id);
$chk->execute();
$chk->store_result();
if ($chk->num_rows > 0) {
    $chk->close();
    Api::error(409, 'DuplicateAssignment', 'An active assignment already exists for this school-unit pair');
}
$chk->close();

$userId = $account->getId();
$stmt = $conn->prepare("
    UPDATE school_unit_assignments
    SET is_active = 'Active', deleted_by = NULL, deleted_at = NULL,
        updated_by = ?, updated_at = NOW()
    WHERE id = ? AND is_active = 'Inactive'
");
$stmt->bind_param('ii', $userId, $id);
if (!$stmt->execute() || $stmt->affected_rows === 0) {
    $stmt->close();
    Api::error(404, 'NotFound', 'Assignment not found in trash.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'restore_school_unit', 'school_unit_assignments', $id);

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