<?php
// tracking.php - Visitor tracking functions

function logVisitor($page = 'Home') {
    // Initialize JSON file if it doesn't exist
    if (!file_exists('stats.json')) {
        $initialData = [
            'settings' => [
                'site_name' => 'My Website',
                'admin_password' => hash('sha256', 'admin123'),
                'timezone' => 'UTC'
            ],
            'visitors' => [],
            'pages' => []
        ];
        file_put_contents('stats.json', json_encode($initialData, JSON_PRETTY_PRINT));
    }
    
    // Get visitor data
    $ip = $_SERVER['REMOTE_ADDR'];
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $referrer = $_SERVER['HTTP_REFERER'] ?? 'Direct';
    $timestamp = date('Y-m-d H:i:s');
    
    // Get geolocation
    $geo = getGeolocation($ip);
    
    $visitorData = [
        'ip' => $ip,
        'user_agent' => $userAgent,
        'referrer' => $referrer,
        'timestamp' => $timestamp,
        'page' => $page,
        'country' => $geo['country'] ?? 'Unknown',
        'city' => $geo['city'] ?? 'Unknown',
        'region' => $geo['region'] ?? 'Unknown'
    ];
    
    // Read existing data
    $stats = json_decode(file_get_contents('stats.json'), true);
    
    // Add new visitor
    array_unshift($stats['visitors'], $visitorData);
    
    // Keep only last 1000 visitors
    $stats['visitors'] = array_slice($stats['visitors'], 0, 1000);
    
    // Update page visits
    if (!isset($stats['pages'][$page])) {
        $stats['pages'][$page] = 0;
    }
    $stats['pages'][$page]++;
    
    // Save data
    file_put_contents('stats.json', json_encode($stats, JSON_PRETTY_PRINT));
}

function getGeolocation($ip) {
    if ($ip === '127.0.0.1' || $ip === '::1') {
        return ['country' => 'Local', 'city' => 'Local', 'region' => 'Local'];
    }
    
    $url = "http://ip-api.com/json/{$ip}";
    $response = @file_get_contents($url);
    
    if ($response) {
        $data = json_decode($response, true);
        if ($data['status'] === 'success') {
            return [
                'country' => $data['country'],
                'city' => $data['city'],
                'region' => $data['regionName']
            ];
        }
    }
    
    return ['country' => 'Unknown', 'city' => 'Unknown', 'region' => 'Unknown'];
}
?>