<?php

require_once __DIR__ . '/_bootstrap.php';
$auth = agent_sync_authenticate($conn);
$acks = $auth['payload']['acks'] ?? [];
if (!is_array($acks)) agent_sync_reply(422, ['ok'=>false,'error'=>'ACKS_REQUIRED']);
$updated = 0;
foreach (array_slice($acks, 0, 100) as $ack) {
  if (!is_array($ack)) continue;
  $eventUuid = trim((string)($ack['event_uuid'] ?? ''));
  $status = strtoupper(trim((string)($ack['status'] ?? 'DONE')));
  if ($eventUuid === '' || !in_array($status, ['DONE','FAILED'], true)) continue;
  $uuidEsc = $conn->real_escape_string($eventUuid);
  $instanceEsc = $conn->real_escape_string($auth['instance_id']);
  $rs = @$conn->query("SELECT id FROM agent_sync_events WHERE event_uuid='{$uuidEsc}' AND instance_id='{$instanceEsc}' AND direction='OUTBOUND' LIMIT 1");
  if ($rs && ($row = $rs->fetch_assoc())) {
    if (ua_agent_sync_mark($conn, (int)$row['id'], $status, $ack['result'] ?? [], (string)($ack['error'] ?? ''))) $updated++;
  }
}
agent_sync_reply(200, ['ok'=>true,'updated'=>$updated]);
