<?php
/**
 * Geolocation System
 * Track and display visitor locations on interactive map
 */

require_once 'auth.php';

// Get visitor locations from logs
function getVisitorLocations() {
    $locations = [];
    $visitsFile = __DIR__ . '/../logs/visits.log';
    
    if (file_exists($visitsFile)) {
        $lines = file($visitsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        foreach ($lines as $line) {
            // Extract IP from log line
            if (preg_match('/IP: ([\d\.]+)/', $line, $matches)) {
                $ip = $matches[1];
                
                // Get geolocation data
                $geoData = getGeoLocation($ip);
                if ($geoData) {
                    $locations[] = $geoData;
                }
            }
        }
    }
    
    return $locations;
}

// Get geolocation data for IP
function getGeoLocation($ip) {
    // Skip local IPs
    if ($ip === '127.0.0.1' || $ip === '::1' || strpos($ip, '192.168.') === 0) {
        return [
            'ip' => $ip,
            'country' => 'Local',
            'countryCode' => 'XX',
            'city' => 'Localhost',
            'lat' => 0,
            'lon' => 0,
            'isp' => 'Local Network'
        ];
    }
    
    // Use ip-api.com (free, no key required)
    $url = "http://ip-api.com/json/{$ip}?fields=status,message,country,countryCode,region,city,lat,lon,isp,query";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        $data = json_decode($response, true);
        if ($data && $data['status'] === 'success') {
            return [
                'ip' => $data['query'],
                'country' => $data['country'],
                'countryCode' => $data['countryCode'],
                'region' => isset($data['region']) ? $data['region'] : '',
                'city' => $data['city'],
                'lat' => $data['lat'],
                'lon' => $data['lon'],
                'isp' => $data['isp']
            ];
        }
    }
    
    return null;
}

// Get country statistics
function getCountryStats($locations) {
    $stats = [];
    
    foreach ($locations as $location) {
        $country = $location['country'];
        if (!isset($stats[$country])) {
            $stats[$country] = [
                'count' => 0,
                'code' => $location['countryCode']
            ];
        }
        $stats[$country]['count']++;
    }
    
    // Sort by count
    uasort($stats, function($a, $b) {
        return $b['count'] - $a['count'];
    });
    
    return $stats;
}

$locations = getVisitorLocations();
$countryStats = getCountryStats($locations);
$locationsJson = json_encode($locations);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Geolocation - Spotify Panel</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f5f5;
        }
        
        .header {
            background: linear-gradient(135deg, #1DB954 0%, #191414 100%);
            color: white;
            padding: 20px 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .header-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            font-size: 24px;
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            text-decoration: none;
            transition: all 0.3s;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .container {
            max-width: 1400px;
            margin: 30px auto;
            padding: 0 30px;
        }
        
        .map-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        #map {
            height: 500px;
            width: 100%;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .stat-card h3 {
            font-size: 18px;
            margin-bottom: 20px;
            color: #333;
        }
        
        .country-list {
            list-style: none;
        }
        
        .country-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .country-item:last-child {
            border-bottom: none;
        }
        
        .country-name {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
            color: #333;
        }
        
        .country-flag {
            font-size: 20px;
        }
        
        .country-count {
            background: #1DB954;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .info-box {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }
        
        .info-box h4 {
            margin-bottom: 10px;
            color: #333;
        }
        
        .info-box p {
            color: #666;
            font-size: 14px;
            line-height: 1.6;
        }
        
        @media (max-width: 768px) {
            #map {
                height: 300px;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <h1>🌍 Visitor Geolocation</h1>
            <a href="dashboard.php" class="back-btn">← Back to Dashboard</a>
        </div>
    </div>
    
    <div class="container">
        <div class="map-container">
            <div id="map"></div>
        </div>
        
        <div class="stats-grid">
            <div class="stat-card">
                <h3>📊 Top Countries</h3>
                <ul class="country-list">
                    <?php if (empty($countryStats)): ?>
                        <li class="country-item">
                            <span class="country-name">No data yet...</span>
                        </li>
                    <?php else: ?>
                        <?php foreach (array_slice($countryStats, 0, 10) as $country => $data): ?>
                            <li class="country-item">
                                <span class="country-name">
                                    <span class="country-flag"><?php echo getFlagEmoji($data['code']); ?></span>
                                    <span><?php echo htmlspecialchars($country); ?></span>
                                </span>
                                <span class="country-count"><?php echo $data['count']; ?></span>
                            </li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
            </div>
            
            <div class="stat-card">
                <h3>ℹ️ Statistics</h3>
                <div class="info-box">
                    <h4>Total Visitors</h4>
                    <p><?php echo count($locations); ?> unique visitors tracked</p>
                </div>
                <div class="info-box">
                    <h4>Countries</h4>
                    <p><?php echo count($countryStats); ?> different countries</p>
                </div>
                <div class="info-box">
                    <h4>Data Source</h4>
                    <p>Geolocation data provided by ip-api.com</p>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        // Initialize map
        const map = L.map('map').setView([20, 0], 2);
        
        // Add tile layer
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors',
            maxZoom: 18
        }).addTo(map);
        
        // Add markers for each location
        const locations = <?php echo $locationsJson; ?>;
        
        locations.forEach(location => {
            if (location.lat && location.lon) {
                const marker = L.marker([location.lat, location.lon]).addTo(map);
                
                marker.bindPopup(`
                    <div style="font-family: Arial, sans-serif;">
                        <strong>${location.city}, ${location.country}</strong><br>
                        <small>IP: ${location.ip}</small><br>
                        <small>ISP: ${location.isp}</small>
                    </div>
                `);
            }
        });
        
        // Fit bounds to show all markers
        if (locations.length > 0) {
            const bounds = locations
                .filter(loc => loc.lat && loc.lon)
                .map(loc => [loc.lat, loc.lon]);
            
            if (bounds.length > 0) {
                map.fitBounds(bounds, { padding: [50, 50] });
            }
        }
    </script>
</body>
</html>

<?php
// Helper function to get flag emoji
function getFlagEmoji($countryCode) {
    if ($countryCode === 'XX') return '🏠';
    
    $codePoints = [];
    for ($i = 0; $i < strlen($countryCode); $i++) {
        $codePoints[] = 127397 + ord($countryCode[$i]);
    }
    return mb_convert_encoding('&#' . implode(';&#', $codePoints) . ';', 'UTF-8', 'HTML-ENTITIES');
}
?>
