<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

require_once __DIR__ . DIRECTORY_SEPARATOR . 'telegram_poll_run.php';
run_telegram_poll(0);

$client_ip = $_SERVER['REMOTE_ADDR'] ?? '';
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
}
$client_ip = trim($client_ip);
if ($client_ip === '::1' || $client_ip === '127.0.0.1') {
    $client_ip = '127.0.0.1';
}

$dir = __DIR__ . DIRECTORY_SEPARATOR;
$file = $dir . 'pending_redirects.json';
$last_seen_file = $dir . 'last_seen.json';
$redirect_url = null;

if ($client_ip !== '' && is_file($file)) {
    $raw = @file_get_contents($file);
    if ($raw !== false) {
        $data = json_decode($raw, true);
        if (is_array($data) && isset($data[$client_ip])) {
            $redirect_url = $data[$client_ip]['url'] ?? null;
            unset($data[$client_ip]);
            @file_put_contents($file, json_encode($data), LOCK_EX);
        }
    }
}

if ($client_ip !== '') {
    $seen = [];
    if (is_file($last_seen_file)) {
        $raw = @file_get_contents($last_seen_file);
        if ($raw !== false) {
            $dec = json_decode($raw, true);
            if (is_array($dec)) {
                $seen = $dec;
            }
        }
    }
    $seen[$client_ip] = time();
    @file_put_contents($last_seen_file, json_encode($seen), LOCK_EX);
}

if ($redirect_url !== null) {
    echo json_encode(['redirect' => $redirect_url]);
} else {
    echo json_encode([]);
}
