<?php
header('Content-Type: application/json');

$dir = __DIR__;
$device = trim($_POST['device_id'] ?? '');

if ($device===''){ echo json_encode(['ok'=>false,'reason'=>'missing device_id']); exit; }

$queueFile = $dir . '/queue_' . preg_replace('/[^a-zA-Z0-9_\-]/','_', $device) . '.json';

if (!is_file($queueFile)){ echo json_encode(['ok'=>false,'reason'=>'no_file','path'=>$queueFile]); exit; }

$json = @file_get_contents($queueFile);
$data = json_decode($json, true);
if (!is_array($data)){ echo json_encode(['ok'=>false,'reason'=>'invalid_json','path'=>$queueFile]); exit; }

$expired = (time() - (int)($data['ts'] ?? 0)) > 300; // 5 minutes
if ($expired){ @unlink($queueFile); echo json_encode(['ok'=>false,'reason'=>'expired','path'=>$queueFile]); exit; }

// consume then return
@unlink($queueFile);
echo json_encode(['ok'=>true,'data'=>$data,'path'=>$queueFile]);
