<?php
require_once __DIR__ . '/../db/config.php';

function track_visitor() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
    // X-Forwarded-For can be a comma-separated list
    $ip = explode(',', $ip)[0];
    
    $session_id = session_id();
    $db = db();

    // Check if we already have this session tracked today
    $stmt = $db->prepare("SELECT id FROM visitor_logs WHERE session_id = ? LIMIT 1");
    $stmt->execute([$session_id]);
    $visitor = $stmt->fetch();

    if ($visitor) {
        // Update activity
        $stmt = $db->prepare("UPDATE visitor_logs SET last_activity = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$visitor['id']]);
    } else {
        // New session, get GeoIP
        $country = 'Unknown';
        $country_code = '??';
        $lat = 0;
        $lon = 0;
        
        // Simple GeoIP via API (Note: This might slow down the first request, but we only do it once per session)
        try {
            $ctx = stream_context_create(['http' => ['timeout' => 2]]);
            $geo = file_get_contents("http://ip-api.com/json/$ip", false, $ctx);
            if ($geo) {
                $data = json_decode($geo, true);
                if ($data && $data['status'] === 'success') {
                    $country = $data['country'];
                    $country_code = $data['countryCode'];
                    $lat = $data['lat'] ?? 0;
                    $lon = $data['lon'] ?? 0;
                }
            }
        } catch (Exception $e) {
            // Silently fail if API is down
        }

        $stmt = $db->prepare("INSERT INTO visitor_logs (ip_address, country, country_code, lat, lon, session_id) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$ip, $country, $country_code, $lat, $lon, $session_id]);
    }
}
