<?php
require_once __DIR__ . '/security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

enrep_require_user();

$data = $_REQUEST['data'] ?? [];
if (!is_array($data)) {
    $data = [];
}

$grouped = [];
foreach ($data as $value) {
    $value = trim((string)$value);
    if (!preg_match('/\A[0-9]+-[0-9]+-[0-9]+-([0-9]+)\z/', $value, $matches)) {
        continue;
    }

    $group = (int)$matches[1];
    if ($group < 1 || $group > 500) {
        continue;
    }

    $grouped[$group][] = $value;
}

ksort($grouped, SORT_NUMERIC);

if (!headers_sent()) {
    header('Content-Type: application/json; charset=utf-8');
}
echo json_encode(array_values($grouped));
