<?php
require_once __DIR__.'/../tracking.php';
emsListenerHeaders(); header('Content-Type: application/json');
try {
    $host = emsListenerHost(); $registered = false;
    foreach (emsTrackingConfig()['accounts'] as $profile) if ($profile['tracking_host'] === $host) $registered = true;
    $secret = (string)getenv('TRACKING_API_BEARER'); $supplied = (string)($_SERVER['HTTP_AUTHORIZATION'] ?? '');
    if (!$registered || strlen($secret) < 43 || strlen($secret) > 256 || !hash_equals('Bearer '.$secret,$supplied)) {
        http_response_code(401); echo '{"error":"unauthorized"}'; exit;
    }
    $db = emsListenerDb(); $stream = emsTrackingConfig()['stream_id'];
    $s = $db->prepare('SELECT last_id,ack_id FROM tracking_optout_stream WHERE stream_id=?'); $s->execute([$stream]); $state = $s->fetch(PDO::FETCH_ASSOC);
    if (!$state) throw new RuntimeException('tracking_stream_unavailable');
    $method = $_SERVER['REQUEST_METHOD'] ?? '';
    if ($method === 'POST') {
        $body = file_get_contents('php://input',false,null,0,1025);
        if (strlen($body) > 1024) throw new RuntimeException('tracking_request_invalid');
        $data = json_decode($body,true,4,JSON_THROW_ON_ERROR);
        if (!is_array($data) || ($data['stream_id'] ?? '') !== $stream || !is_int($data['ack_id'] ?? null)
            || $data['ack_id'] < 0 || $data['ack_id'] > (int)$state['last_id']) throw new RuntimeException('tracking_request_invalid');
        $s = $db->prepare('UPDATE tracking_optout_stream SET ack_id=GREATEST(ack_id,?),ack_at_utc=UTC_TIMESTAMP(6) WHERE stream_id=?');
        $s->execute([$data['ack_id'],$stream]);
        echo json_encode(['stream_id'=>$stream,'acknowledged'=>true],JSON_THROW_ON_ERROR);
    } elseif ($method === 'GET') {
        $after = $_GET['after'] ?? '0';
        if (!is_string($after) || !preg_match('/^(?:0|[1-9][0-9]{0,18})$/D',$after)
            || filter_var($after,FILTER_VALIDATE_INT,['options'=>['min_range'=>0]]) === false
            || (int)$after > (int)$state['last_id']) throw new RuntimeException('tracking_cursor_invalid');
        $s = $db->prepare('SELECT id,token_hash,sealed_token,confirmation_method,received_at_utc FROM tracking_optout_events WHERE stream_id=? AND id>? AND id<=? ORDER BY id LIMIT 50');
        $s->execute([$stream,(int)$after,$state['last_id']]); $rows = $s->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as &$row) $row['id'] = (int)$row['id']; unset($row);
        $s = $db->prepare('SELECT received_at_utc FROM tracking_optout_events WHERE stream_id=? AND id>? ORDER BY id LIMIT 1');
        $s->execute([$stream,$state['ack_id']]);
        echo json_encode(['version'=>1,'stream_id'=>$stream,'head_id'=>(int)$state['last_id'],'ack_id'=>(int)$state['ack_id'],
            'oldest_unacknowledged_at_utc'=>$s->fetchColumn() ?: null,'events'=>$rows],JSON_THROW_ON_ERROR);
    } else { header('Allow: GET, POST'); http_response_code(405); echo '{"error":"method_not_allowed"}'; }
} catch (Throwable $e) { error_log('tracking_optout_api_unavailable'); http_response_code(503); echo '{"error":"unavailable"}'; }
