<?php
// Save visitor data to JSON files
header('Content-Type: application/json');

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

// Get visitor info
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]);
    }

    // Get location info
    $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 detection
    $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();
        $visitorInfo = getVisitorInfo();
        $sessionId = session_id();
        
        // Create visitor record
        $record = [
            'session_id' => $sessionId,
            'page' => $input['page'],
            'data' => $input['data'],
            'visitor_info' => $visitorInfo,
            'timestamp' => date('Y-m-d H:i:s'),
            'last_seen' => time()
        ];
        
        // Save to individual page file
        $pageFile = "Data/{$input['page']}_" . date('Y-m-d') . ".json";
        $pageData = [];
        
        if (file_exists($pageFile)) {
            $pageData = json_decode(file_get_contents($pageFile), true) ?: [];
        }
        
        $pageData[] = $record;
        file_put_contents($pageFile, json_encode($pageData, JSON_PRETTY_PRINT));
        
        // Save to master visitors file
        $masterFile = "Data/all_visitors_" . date('Y-m-d') . ".json";
        $masterData = [];
        
        if (file_exists($masterFile)) {
            $masterData = json_decode(file_get_contents($masterFile), true) ?: [];
        }
        
        $masterData[] = $record;
        file_put_contents($masterFile, json_encode($masterData, JSON_PRETTY_PRINT));
        
        // Also save to live visitors for real-time tracking
        $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['data'] = $input['data'];
                $visitor['timestamp'] = date('Y-m-d H:i:s');
                $visitor['last_seen'] = $currentTime;
                $visitor['status'] = 'online';
                $found = true;
                break;
            }
        }
        
        if (!$found) {
            $record['status'] = 'online';
            $liveData[] = $record;
        }
        
        file_put_contents($liveFile, json_encode($liveData, JSON_PRETTY_PRINT));
        
        echo json_encode(['status' => 'success', 'message' => 'Data saved successfully']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No data received']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>