<?php

require_once __DIR__ . '/_bootstrap.php';
$auth = agent_sync_authenticate($conn);
$instanceEsc = $conn->real_escape_string($auth['instance_id']);
$events = [];
$rs = @$conn->query("SELECT id,event_uuid,event_type,entity_type,entity_id,payload_json,created_at FROM agent_sync_events WHERE instance_id='{$instanceEsc}' AND direction='OUTBOUND' AND status IN ('PENDING','FAILED') AND available_at<=NOW() ORDER BY id ASC LIMIT 100");
if ($rs) while ($row = $rs->fetch_assoc()) {
  $row['payload'] = json_decode((string)$row['payload_json'], true) ?: [];
  unset($row['payload_json']);
  $events[] = $row;
}
agent_sync_reply(200, ['ok'=>true,'events'=>$events,'server_time'=>time()]);
