<?php
// Live visitor tracking for admin panel
header('Content-Type: application/json');

// Create Data directory if it doesn't exist
if (!is_dir('Data')) {
    mkdir('Data', 0755, true);
}

function getVisitorInfo() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
        $ip = trim($ips[0]);
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ips[0]);
    }

    $locationData = @file_get_contents("http://ip-api.com/json/{$ip}?fields=status,country,regionName,city,isp,mobile,proxy");
    $location = json_decode($locationData, true);

    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    
    $device = "Desktop";
    $os = "Unknown";
    
    if (preg_match('/Windows NT/i', $userAgent)) {
        $os = "Windows";
    } elseif (preg_match('/Mac OS X/i', $userAgent)) {
        $os = "macOS";
    } elseif (preg_match('/Linux/i', $userAgent)) {
        $os = "Linux";
    } elseif (preg_match('/Android/i', $userAgent)) {
        $os = "Android";
        $device = "Mobile";
    } elseif (preg_match('/iPhone|iPad/i', $userAgent)) {
        $os = "iOS";
        $device = preg_match('/iPad/i', $userAgent) ? "Tablet" : "Mobile";
    }

    return [
        'ip' => $ip,
        'country' => ($location && $location['status'] == 'success') ? $location['country'] : 'Unknown',
        'city' => ($location && $location['status'] == 'success') ? $location['city'] : 'Unknown',
        'region' => ($location && $location['status'] == 'success') ? $location['regionName'] : 'Unknown',
        'isp' => ($location && $location['status'] == 'success') ? $location['isp'] : 'Unknown',
        'device' => $device,
        'os' => $os,
        'user_agent' => $userAgent,
        'timestamp' => date('Y-m-d H:i:s')
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if ($input) {
        session_start();
        $sessionId = session_id();
        $visitorInfo = getVisitorInfo();
        
        // Create live visitor record
        $record = [
            'session_id' => $sessionId,
            'page' => $input['page'],
            'action' => $input['action'],
            'visitor_info' => $visitorInfo,
            'timestamp' => date('Y-m-d H:i:s'),
            'last_seen' => time(),
            'status' => 'online'
        ];
        
        // Save to live visitors file
        $liveFile = "Data/live_visitors.json";
        $liveData = [];
        
        if (file_exists($liveFile)) {
            $liveData = json_decode(file_get_contents($liveFile), true) ?: [];
        }
        
        // Remove old entries (older than 60 seconds)
        $currentTime = time();
        $liveData = array_filter($liveData, function($visitor) use ($currentTime) {
            return ($currentTime - $visitor['last_seen']) < 60;
        });
        
        // Update or add current visitor
        $found = false;
        foreach ($liveData as &$visitor) {
            if ($visitor['session_id'] === $sessionId) {
                $visitor['page'] = $input['page'];
                $visitor['action'] = $input['action'];
                $visitor['timestamp'] = date('Y-m-d H:i:s');
                $visitor['last_seen'] = $currentTime;
                $visitor['status'] = 'online';
                $found = true;
                break;
            }
        }
        
        if (!$found) {
            $liveData[] = $record;
        }
        
        file_put_contents($liveFile, json_encode($liveData, JSON_PRETTY_PRINT));
        
        // Also save to daily log
        $dailyFile = "Data/daily_activity_" . date('Y-m-d') . ".json";
        $dailyData = [];
        
        if (file_exists($dailyFile)) {
            $dailyData = json_decode(file_get_contents($dailyFile), true) ?: [];
        }
        
        $dailyData[] = $record;
        file_put_contents($dailyFile, json_encode($dailyData, JSON_PRETTY_PRINT));
        
        echo json_encode(['status' => 'success', 'session_id' => $sessionId]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No data received']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>